Where did this constant come from?

D

David Masover

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
 
H

Heesob Park

Hi,

2008/8/18 David Masover said:
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
 
I

Ilan Berci

David said:
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
 

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

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top