Updated: Ruby: Debugging a method's source location and code

Posted . Visible to the public. Auto-destruct in 33 days

Newer Rails projects come with a gem that allows you to access .method(:foo).source. Added a corresponding section to a fitting card

Changes

  • +## Access the `Method` object
  • Dead simple: Get the method object and ask for its owner:
  • -"foo".method(:upcase)
  • - => #<Method: String#upcase>
  • -"foo".method(:upcase).owner
  • - => String
  • +```rb
  • +"foo".method(:upcase)
  • +# => #<Method: String#upcase>
  • +
  • +"foo".method(:upcase).owner
  • +# => String
  • +```
  • +
  • +## Look up a method's source location
  • +
  • Ruby 1.9 adds a method `Method#source_location` that returns file and line number where that method is defined.
  • -class Example; def method() end end
  • - => nil
  • -Example.new.method(:method).source_location
  • - => ["(irb)", 11]
  • -
  • -"foo".method(:upcase).source_location
  • - => nil # String#upcase is a native method that's defined in C
  • -
  • -Rumor has it in Ruby 1.8 there is a gem `ruby18_source_location` that does something similar.
  • +```rb
  • +class Example; def method() end; end
  • +# => nil
  • +
  • +Example.new.method(:method).source_location
  • +# => ["(irb)", 11]
  • +
  • +"foo".method(:upcase).source_location
  • +# => nil # String#upcase is a native method that's defined in C
  • +```
  • +
  • +## Look up a method's source code
  • +
  • +If your Gemfile comes with [method_source](https://rubygems.org/gems/method_source) (a dependency of Rails 7+), you can can use inspect the source code directly using the `Method#source` method:
  • +
  • +```rb
  • +puts User.new.method(:name).source
  • +
  • +# =>
  • +# def name
  • +# "#{first_name} #{last_name}".strip
  • +# end
  • +```
  • ---
  • ## Also see
  • + [Using Ruby's Method objects for inspecting methods](https://makandracards.com/makandra/610159-using-the-ruby-s-class-method-for-inspecting-and-debugging-methods)
  • + [How to examine an unknown Ruby object](https://makandracards.com/makandra/55983-how-to-examine-an-unknown-ruby-object)
Michael Leimstädtner
License
Source code in this card is licensed under the MIT License.
Posted by Michael Leimstädtner to makandra dev (2024-10-25 13:37)