Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

constants

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.

like image 564
Minqi Pan Avatar asked Mar 26 '12 08:03

Minqi Pan


People also ask

How do you find the constants in Ruby?

Ruby Constants Constants begin with an uppercase letter. Constants defined within a class or module can be accessed from within that class or module, and those defined outside a class or module can be accessed globally. Constants may not be defined within methods.

Are constants global in Ruby?

Although constants look like local variables with capital letters, they have the visibility of global variables: they can be used anywhere in a Ruby program without regard to scope.

How do you convert a string to a constant in Ruby?

No need to require ActiveSupport. Usage example: class User; def self. lookup; const_get('SomeClassName);end; end User. lookup will return class itself.

Do not define constants this way within a block rails?

From the docs: Do not define constants within a block, since the block's scope does not isolate or namespace the constant in any way. If you are trying to define that constant once, define it outside of the block instead, or use a variable or method if defining the constant in the outer scope would be problematic.


1 Answers

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

like image 129
Alex Avatar answered Oct 03 '22 22:10

Alex