Ruby Tips - How to figure out where a method is defined

Ruby Tips - How to figure out where a method is defined

The other day when I was dabbling with the huge codebase, I was wondering where a particular method was being declared for a specific method
Software Development
Like
by Jey Geethan | August 12, 2018

The other day when I was dabbling with the huge codebase, I was wondering where a particular method was being declared for a specific method. I wanted to know this because my greps didn't turn out to volatile and didn't return any results.

The Solution

The Ruby interpreter has certain methods that can be used for identifying under which module or class, the particular method is being defined. See the example below.

module Foo
  def say_hello
    puts "hello"
  end
end
	

class Bar
  include Foo
end
	

puts Bar.new.method(:say_hello)                   #=> #<Method: Bar(Foo)#say_hello>
puts Bar.new.method(:say_hello).source_location   #=> hello.rb


So using the .source_location you will be able to figure which file it has been declared.


Jey Geethan

Jey Geethan is a poet, author and an entrepreneur.


Related Articles

Software Development

Ruby on Rails - Complex route constraints made easy

by Jey Geethan | March 31, 2019
Ruby on Rails - Complex route constraints made easy
In Rails, we know that the routes are the most important entry-point where we define the which url hits which controller. We also know how to define the resources and add some conditions to the routing.
Software Development

[.NET Error] Update requires a valid UpdateCommand when passed DataRow collection with modified rows

by Jey Geethan | March 06, 2008
[.NET Error] Update requires a valid UpdateCommand when passed DataRow collection with modified rows
This is an error, with which i was dumbfounded for weeks. But the solution is simple after understanding why it's happening