Where did this constant come from?

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

Hi,

2008/8/18 David M. [email protected]:

 parts.tap(&:pop).join('::').constantize
   break unless ancestor.const_defined? name
 Object

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 H.

David M. 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… :slight_smile:

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