How do I find where a constant is defined in Ruby? How do I find where a constant is defined in Ruby? ruby ruby

How do I find where a constant is defined in Ruby?


In ruby, $"holds all the file names that are loaded via Kernel.load.So you could try something like this:

constant = User$".detect{|load_path|  load_path.include?(constant.to_s.underscore)}

Note: The method underscore is part of Rails/ActiveSupport


There is a better way to do this as of Ruby 2.7, which is Module.const_source_location.

> Admin.const_source_location(:LIMIT)#=> ["SOME_PATH/user.rb", 2]

References:


Use ack, sometimes if I reach the limits of Pry (and Ruby) i resort to using it. Great thing about it is you can invoke it from within Pry itself using its shell integration features, usually just typing .ack ClassName does the trick, however it requires that the class is defined in a file under the current directory.

In the case that the class is not defined in the current directory, then you can always resort to look up one of its methods, take the source location from there, and then use Pry's cat command to display it (with syntax highlighting) or Pry's edit command to jump directly to its definition.

The case where a class does NOT have any instance methods defined is fairly rare -- and such a class is usually quite uninteresting anyway :)

EDIT:

The most recent version of Pry (0.9.9) can now show the source for modules/classes using the normal show-source command. It requires that the module/class has at least one defined method however