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



On 3/30/07, ara.t.howard@xxxxxxxx <ara.t.howard@xxxxxxxx> wrote:
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'

I don't think that's what he's looking for.

He has a string containing Ruby source code which presumably defines a
class (or classes?) which might be contained within a module. He
want's to find the fully qualified name of this unknown class (or
classes?).

The A::B is really just an example.

WHY he wants to do this is beyond me.

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/

.



Relevant Pages

  • Taint (like in Perl) as a Python module: taint.py
    ... The following is my first attempt at adding a taint feature to Python ... string to create a safe string from it. ... def replace: ...
    (comp.lang.python)
  • Memory Question
    ... I have wrote a helper to my program which monitors object count, memory utilization and a threshold of 10% to determine how many objects are sticking around and how many are being garbage collected. ... occured right before the original String count). ... def print_threshold_breakers hsh1, hsh2, threshold ... putsf 'Building mem usage', mem_usage ...
    (comp.lang.ruby)
  • Re: [QUIZ] Editing Text (#145)
    ... I start by partially implementing a string class that works equally ... a single "gap" and recirculates unused space better. ... def inspect ... # remove excess trailing space if too much ...
    (comp.lang.ruby)
  • Re: Named/positional method args
    ... duck-typing isn't going to do a bit of good ... if one of those is passed in instead of the String representation. ... def to_file; self end ... It's not really limiting to specify types in method interfaces. ...
    (comp.lang.ruby)
  • UnicodeEncodeError in Windows
    ... def getdamage: ... """reads each line of war report ... """Build a string from a warrior's stats ... As I understand it the error is related to the ascii codec being ...
    (comp.lang.python)