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

M

Mike Austin

'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
 
A

ara.t.howard

'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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,534
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top