# How to find which source file defines a constant?

**URL:** <https://www.ruby-forum.com/t/how-to-find-which-source-file-defines-a-constant/143384>\
**Category:** Ruby\
**Created:** [July 17, 2008, 10:25pm UTC](https://www.ruby-forum.com/t/how-to-find-which-source-file-defines-a-constant/143384 "2008-07-17T22:25:13Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![s0nspark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f475e1/32.png) [@s0nspark](https://www.ruby-forum.com/u/s0nspark)\
**Post date:** [July 17, 2008, 10:25pm UTC](https://www.ruby-forum.com/t/how-to-find-which-source-file-defines-a-constant/143384/1 "2008-07-17T22:25:13Z")

</div>

Is there a straightforward way to find out (programatically) which  
loaded source file has defined a given constant?

Thanks,  
Tim

---

<div class="post-metadata">

**Author:** ![s0nspark](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/s/f475e1/32.png) [@s0nspark](https://www.ruby-forum.com/u/s0nspark)\
**Post date:** [July 18, 2008, 2:21pm UTC](https://www.ruby-forum.com/t/how-to-find-which-source-file-defines-a-constant/143384/2 "2008-07-18T14:21:03Z")

</div>

I managed to hack something together based on the loaded modules array  
($"), as seen in this extracted snippet:

src = File.read(rakefile).split("\n")  
ver = scan\_for\_version(src)  
if ver =~ /VERSION/ # find out which file defines version  
loaded = $".dup # currently loaded files  
load rakefile, true  
# currently loaded - previously loaded - rakefile = candidates  
($" - loaded - [rakefile]).each { |new\_file|  
src = File.read(new\_file).split("\n")  
ver = scan\_for\_version(src)  
if ver  
version\_file = new\_file.gsub(Dir.pwd + “/”, ‘’)  
break  
end  
}  
end

… where scan\_for\_version does a simple line by line regex check to try  
to find and extract the value of a VERSION constant that may be defined  
in the given file source.

I probably should have mentioned that my aim here is to update the  
constant from a script outside of the codebase in question… this is  
part of a script to automate the tagging, branching, archiving, and  
deployment as part of our release process. In the given case, I am  
looking in the project Rakefile to see if version is defined there or if  
it is loaded from somewhere else in the codebase.

Aside from my general satisfaction at having something that works …  
(yay!) … I must admit I am not really _enthused_ with my solution. It  
seems there should be some way to tap the interpreter’s internals for an  
explicit answer, assuming such things are actually stored in there in  
some fashion 🙂

Any other ideas?

Cheers,  
Tim
