Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

See where a symbol is defined in irb

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
like image 643
Vlad the Impala Avatar asked Nov 14 '22 08:11

Vlad the Impala


1 Answers

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.

like image 145
YenTheFirst Avatar answered Dec 01 '22 00:12

YenTheFirst