DEV Community

James
James

Posted on • Originally published at jsrn.net on

4 2

Finding A Method Declaration With Source Location

I recently had one of those moments where some code failed, but not in the way I expected it to. To create a contrived example, the scenario was basically this:

class LocationsController < ApplicationController
  def update
    my_location = Location.find(params[:id])
    do_something_with(location)
  end
end
Enter fullscreen mode Exit fullscreen mode

This code won’t do what I want it to because I have defined the variable my_location but then passed location to another method. What I initially expected upon finding the bug is that I would have seen a NameError complaining that the local variable location didn’t exist. But I didn’t. As far as I could tell, location existed and it was nil.

It wasn’t referenced anywhere else in LocationsController, nor in ApplicationController. So what is it? Fortunately, Ruby provides a great way to find out.

class LocationsController < ApplicationController
  def update
    puts method(:location).source_location
    # "/usr/local/bundle/gems/actionpack-5.0.7.2/lib/action_controller/metal.rb"
    # 149
  end
end
Enter fullscreen mode Exit fullscreen mode

That’s that mystery solved. There is a method called location implemented a layer or two up the inheritance hierarchy. We knew it had to come from somewhere, but source_location lets us determine the exact location.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay