Ruby 2.7 adds Module#const_source_location

Sometimes it is difficult to find out the source location of methods by just looking at the class documentation,
as the method could be dynamically defined at many place like in modules, parent classes etc.

That is why ruby provides Method#source_location to retrieve the source location where a method is defined.

Let’s say we have the following classes:

# user.rb
class User
  LIMIT =  10

  def full_name(first_name, last_name)
    "#{first_name} #{last_name}"

# admin.rb
class Admin < User

If we want to find the source location of method full_name by using Admin object. We can easily find out using Method#source_location.

#=> ["SOME_PATH/user.rb", 4]

It returns the file path and line number where method is defined.

This was only limited to methods though. We had no way to retrieve the source location of LIMIT constant from our example.


Ruby 2.7 has now added Module#const_source_location similar to Method#source_location which returns the source location of a constant.

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

It returns the file path and line number where a constant is defined similar to Method#source_location.

We can also find the location of classes and modules using const_source_location.

# Pass a class constant
> Module.const_source_location(:Admin)
#=> ["SOME_PATH/admin.rb", 1]

# Pass constant as string
> Module.const_source_location("Admin")
#=> ["SOME_PATH/admin.rb", 1]

const_source_location available to call from Objects.

# Pass a class constant
> Object.const_source_location(:Admin)
#=> ["SOME_PATH/admin.rb", 1]

# Pass constant as string
> Object.const_source_location("Admin")
#=> ["SOME_PATH/admin.rb", 1]

In the event the a constant is not defined, nil is returned.

> Module.const_source_location(:Score)
#=> nil

Need help on your Ruby on Rails or React project?

Join Our Newsletter