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
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.


Related Articles

What's next after Chatbots?
Software Development

What's next after Chatbots?

by Jey Geethan | December 08, 2018
Chatbots are programmatically defined workflows that can help any customer to navigate some scenarios. But will chatbots stay there?

Ruby on Rails Engine - How To Keep Your Engine Migrations Abstracted From Your Host Rails App
Software Development

Ruby on Rails Engine - How To Keep Your Engine Migrations Abstracted From Your Host Rails App

by Jey Geethan | January 16, 2019
Have you ever worked on building a Rails Engine and wanted to keep the models, the migrations and everything inside the engine rather than using a generator to copy paste them into your host Rails App?