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