Getting the name of a class that's in a module

Discussion in 'Ruby' started by Mike Austin, Mar 17, 2006.

  1. Mike Austin

    Mike Austin Guest

    'some_object.class.to_s' doesn't work because it returns the entire hierarchy,
    i.e 'SomeModule::SomeClass'. I could do some string ops on that but it seems
    there would be an easier way. Here's an example:

    class MenuStyle
    class Button < Style
    end
    end

    class View
    def initialize()
    @delegate = MenuStyle.const_get( self.class.to_s )
    end
    end


    Thanks,
    Mike
    Mike Austin, Mar 17, 2006
    #1
    1. Advertising

  2. Mike Austin

    Guest

    On Sat, 18 Mar 2006, Mike Austin wrote:

    > 'some_object.class.to_s' doesn't work because it returns the entire
    > hierarchy, i.e 'SomeModule::SomeClass'. I could do some string ops on that
    > but it seems there would be an easier way. Here's an example:
    >
    > class MenuStyle
    > class Button < Style
    > end
    > end
    >
    > class View
    > def initialize()
    > @delegate = MenuStyle.const_get( self.class.to_s )
    > end
    > end


    harp:~ > cat a.rb
    #
    # creates a class by class name
    #
    def klass_stamp(hierachy, *a, &b)
    ancestors = hierachy.split(%r/::/)
    parent = Object
    while((child = ancestors.shift))
    klass = parent.const_get child
    parent = klass
    end
    klass::new(*a, &b)
    end

    hth.

    -a
    --
    share your knowledge. it's a way to achieve immortality.
    - h.h. the 14th dali lama
    , Mar 17, 2006
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Marc E
    Replies:
    8
    Views:
    389
    Thomas Hawtin
    Nov 28, 2005
  2. Ilariu Raducan
    Replies:
    2
    Views:
    341
    Ilariu Raducan
    Jul 14, 2004
  3. Replies:
    2
    Views:
    91
  4. Jari Williamsson

    Getting class name without module

    Jari Williamsson, Feb 12, 2008, in forum: Ruby
    Replies:
    3
    Views:
    195
    Robert Klemme
    Dec 5, 2012
  5. Iñaki Baz Castillo
    Replies:
    6
    Views:
    145
    Iñaki Baz Castillo
    Mar 31, 2009
Loading...

Share This Page