[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Where did this constant come from?

David Masover

8/17/2008 5:38:00 PM

What's the simplest way to find out where a constant was defined?

I did come up with a way (probably partly ripped off from ActiveSupport), but
it feels convoluted and fragile:


class Module
def parent_namespace
parts = self.name.split('::')
if parts.length > 1
parts.tap(&:pop).join('::').constantize
else
nil
end
end

def eldest_ancestor_with_const name
if const_defined? name
klass = self
self.ancestors.each do |ancestor|
break if klass == Object
break unless ancestor.const_defined? name
klass = ancestor
end
klass
else
nil
end
end

def find_const_parent name
if Object.const_defined? name
Object
else
klass = self
until klass.const_defined? name
klass = klass.parent_namespace
return nil if klass.nil?
end

klass.eldest_ancestor_with_const(name)
end
end
end

2 Answers

Heesob Park

8/18/2008 1:57:00 AM

0

Hi,

2008/8/18 David Masover <ninja@slaphack.com>:
> What's the simplest way to find out where a constant was defined?
>
> I did come up with a way (probably partly ripped off from ActiveSupport), but
> it feels convoluted and fragile:
>
>
> class Module
> def parent_namespace
> parts = self.name.split('::')
> if parts.length > 1
> parts.tap(&:pop).join('::').constantize
> else
> nil
> end
> end
>
> def eldest_ancestor_with_const name
> if const_defined? name
> klass = self
> self.ancestors.each do |ancestor|
> break if klass == Object
> break unless ancestor.const_defined? name
> klass = ancestor
> end
> klass
> else
> nil
> end
> end
>
> def find_const_parent name
> if Object.const_defined? name
> Object
> else
> klass = self
> until klass.const_defined? name
> klass = klass.parent_namespace
> return nil if klass.nil?
> end
>
> klass.eldest_ancestor_with_const(name)
> end
> end
> end
>
>
Something like this:

def find_const_parent(name)
Object.constants.select do |x|
x=eval(x)
[Class,Module].include?(x.class) && x.const_defined?(name)
end
end


Regards,

Park Heesob

Ilan Berci

8/18/2008 8:02:00 PM

0

David Masover wrote:
> What's the simplest way to find out where a constant was defined?
>
> I did come up with a way (probably partly ripped off from
> ActiveSupport), but
> it feels convoluted and fragile:


just install the gem rak and grep for it.. :)


I do this all the time when I have to go into AR..
cd /usr/lib/ruby/gems/1.8/gems/activerecord/lib
rak <constant_name>

done



--
Posted via http://www.ruby-....