# Where did this constant come from?

**URL:** <https://www.ruby-forum.com/t/where-did-this-constant-come-from/146090>\
**Category:** Ruby\
**Created:** [August 17, 2008, 7:41pm UTC](https://www.ruby-forum.com/t/where-did-this-constant-come-from/146090 "2008-08-17T19:41:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![dgm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/df788c/32.png) [@dgm](https://www.ruby-forum.com/u/dgm)\
**Post date:** [August 17, 2008, 7:41pm UTC](https://www.ruby-forum.com/t/where-did-this-constant-come-from/146090/1 "2008-08-17T19:41:49Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![dgm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/df788c/32.png) [@dgm](https://www.ruby-forum.com/u/dgm)\
**Post date:** [August 18, 2008, 4:00am UTC](https://www.ruby-forum.com/t/where-did-this-constant-come-from/146090/2 "2008-08-18T04:00:44Z")

</div>

Hi,

2008/8/18 David M. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid):

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

---

<div class="post-metadata">

**Author:** ![dgm](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/df788c/32.png) [@dgm](https://www.ruby-forum.com/u/dgm)\
**Post date:** [August 18, 2008, 10:05pm UTC](https://www.ruby-forum.com/t/where-did-this-constant-come-from/146090/3 "2008-08-18T22:05:07Z")

</div>

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… 🙂

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
