Heesob Park
8/18/2008 1:57:00 AM
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