Re: Find the fully qualified name of a class from a string



On Sat, 31 Mar 2007, Nasir Khan wrote:

Say you have a class definition in a string -

str = <<EOF
module A
class B
def b
puts "hello"
end
end
end
EOF

What is the easiest way to find out the fully qualified name of the class
there, namely "A::B"

Now I could do a thing like

module EmptyModule
end

EmptyModule.module_eval(str)

def self.find_class mod
mod.constants.each do |str|
m = mod.const_get(str)
if m.class == Module
find_class(m)
else
cname = m.to_s
puts cname.match(/EmptyModule::/).post_match
break
end
end
end

and call this method

find_class(EmptyModule)

which prints "A::B"

This works but it seems too much work to do something simple.

Is there a better/simpler way to do this?

Thanks
Nasir

harp:~ > cat a.rb
#
# a better const_get
#
def constant_get(hierachy)
ancestors = hierachy.split(%r/::/)
parent = Object
while((child = ancestors.shift))
klass = parent.const_get child
parent = klass
end
klass
end

c = constant_get 'A::B'



-a
--
be kind whenever possible... it is always possible.
- the dalai lama

.



Relevant Pages

  • questions about Class#remove_class implementation
    ... def remove_class ... next unless parent.const_defined?&& klass = parent.const_get ... When could parent == klass hold at the end of the block? ...
    (comp.lang.ruby)
  • Re: Getting the name of a class thats in a module
    ... I could do some string ops on that but it seems there would be an easier way. ... def klass_stamp ... parent = Object ... klass = parent.const_get child ...
    (comp.lang.ruby)
  • Re: Algorithm for Labels like in Gmail
    ... I'm trying to make a simple Contact Manager using python (console ... or "Labels" just like in Gmail. ... def get_bases: ... contacts.create, ('first_name', str), ...
    (comp.lang.python)
  • Re: Postscript XObjects: invalidaccess in def
    ... i try to add Postscript code to a PDF file with the iText Java PDF ... Always i use "def" the following error appears: ... input str readline ... in the topmost dictionary on the dictionary stack. ...
    (comp.lang.postscript)
  • Re: Dynamically generating classes?
    ... >> def initialize ... > def create_class(name, parent = nil) ... > klass = Class.new ... "MyClass" ...
    (comp.lang.ruby)