See where a symbol is defined in irb
Asked Answered
O

3

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
Oao answered 30/3, 2012 at 0:8 Comment(1)
Have you tried just grepping for "SOME_CONSTANT =" in your directory?Quadricycle
I
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.

Imperforate answered 30/3, 2012 at 1:42 Comment(0)
T
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.

Tove answered 30/3, 2012 at 0:30 Comment(0)
G
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).

Genu answered 30/3, 2012 at 13:16 Comment(1)
According to https://mcmap.net/q/92738/-how-to-find-where-a-method-is-defined-at-runtime there is (now) a gem ruby18_source_location that backports Method#source_location.Esoteric

© 2022 - 2024 — McMap. All rights reserved.