Tip: If you think you’re going insane, check object.method(:method_name).source_location

Last night I updated an app to Rails 4, and was about to pull my hair out and file a bug in ActiveRecord because the 4.1.5 change mysteriously broke my user authentication - and the stack trace, about a method missing that was clearly in the ActiveRecord source code, made absolutely zero sense.

As it turned out, the change broke an obscure gem that I'd been using (routing_concerns - don't use it!), and since it seemed to have nothing to do with ActiveRecord, I had no idea that it had been shadowing an internal module with its own version that was missing that method! But how I ended up tracking it down is the tip here.

As it turns out, once you drop into a debugger like [byebug](https://github.com/deivid-rodriguez/byebug), you can call the method `method` on any object, passing a symbol for the method name, and then call `source_location` on the resulting object... and it tells you exactly which gem and file is responsible for that method's implementation. For instance, where self is an ActiveRecord instance:

(byebug) self.method(:sanitize_for_mass_assignment).parameters
[[:req, :new_attributes], [:opt, :options]]
(byebug) self.method(:sanitize_for_mass_assignment).source_location
["/Users/btown/.rvm/gems/ruby-2.1.2/gems/routing_concerns-0.1.0/lib/active_model/forbidden_attributes_protection.rb", 6]

You may find that this tells you exactly why nothing was behaving as you'd expect from the source code!

4 thoughts on “Tip: If you think you’re going insane, check object.method(:method_name).source_location”

  1. I love this tip, and I love telling people about it. Thanks for getting around it posting on Reddit before I did 🙂

    One additional note, in many terminals (I use iTerm2), ⌘-Click will open that right in your default editor. Boom, API documentation from anywhere.


Leave a Comment