How to find which source file defines a constant?

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

Thanks,
Tim

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 :slight_smile:

Any other ideas?

Cheers,
Tim

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs