6

I work on a pretty large rails project at work. Sometimes I need to hunt down class / constant definitions. Is there some built-in method in Ruby to do this for me? Example:

irb> SOME_CONSTANT.__file__
=> /some/path/to/a/file
Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124

3 Answers3

2

This isn't exactly what you're looking for, but methods do have a .source_location method on them. You can use this to find out where a class is actually implemented. (Since ruby lets you reopen classes, this could be in multiple places)

for example, given an instance of an object, i:

i.methods.map do |method_name| 
  method_obj = i.method(method_name)
  file, line = method_obj.source_location
  file #map down to the file name
end.uniq

will give you a list of all the files where i's methods are implemented.

This will work for classes that have at least 1 method implemented in ruby. It won't work for constants, though.

Felixyz
  • 19,053
  • 14
  • 65
  • 60
YenTheFirst
  • 2,172
  • 13
  • 11
1

At the very beginning before any file is loaded, insert a line that defines the class/constant that you want to check as something other than a module. For example, suppose you have class or other kind of constant A within your code, and want to know where it is defined. Then, at the very beginning of the main file, write

A = nil

Then, when the program is run, whenever it first meets the definition of class/constant A, it will show something like

some_path_to_a_file:line_number in `some_method': A is not a class (TypeError)

or

some_path_to_a_file:line_number: warning: already initialized constant A

Then, some_path_to_a_file:line_number will be the location where A is defined.

sawa
  • 165,429
  • 45
  • 277
  • 381
0

If you're using Ruby 1.9.2, @YenTheFirst's answer is correct: call #source_location on a Method object.

If you're using Ruby 1.8.7, then #source_location doesn't exist (yet). You'll need something like this implementation of a method. (There's another one or two floating around, but I can't find the other one real quick).

RyanWilcox
  • 13,890
  • 1
  • 36
  • 60
  • 1
    According to http://stackoverflow.com/a/13015691/260122 there is (now) a gem [ruby18_source_location](https://github.com/ConradIrwin/ruby18_source_location) that backports `Method#source_location`. – clacke Nov 15 '13 at 20:30