Search code examples
rubyconstants

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


Using pry, it's very simple to find where a method is defined and see the source by edit-method command. Yet there is no correspondence for class itself. When that class has no methods defined itself, it's hard to locate the source through pry.

Classes are constants, so it's equivalent to ask where to find the source in which a particular Ruby constant is defined. Thank you very much.


Solution

  • 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