How to find which source file defines a constant?

T

Tim Ferrell

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

Thanks,
Tim
 
T

Tim Ferrell

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
 

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

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,662
Latest member
salsusa

Latest Threads

Top