Legacy Code: Diving into Source Code

Published Feb 17, 2017Last updated Feb 21, 2017
Legacy Code: Diving into Source Code

How many times have you been thrown into the deep end of legacy code? How many times have you wondered where on earth a method was defined? Did someone try to be cool and metaprogrammed the app into oblivion?

These are questions I often deal with when dealing with legacy code — let me tell you, it isn't fun. Though it's not fun, I do like the challenge. Today, we will talk about an invaluable method that has been a lifesaver for me throughout the years: source_location.

This is extremely valuable when I'm trying to debug code or even just trying to understand what is happening to a certain snippet. The way to call it is to: (1) know what method you're trying to locate and (2) call source_location on it.

Examples! Let's dive in!

One time, I was trying to debug a class that suddenly blew up the moment I tried to print it out. I tried looking at the stacktrace to see what the problem was. Unfortunately, going to the specific lines in the stacktrace was for naught as it just showed some lines inside rails or a gem (I forgot which).

The first clue came to me when I realised I was just trying to inspect the model:

> thing = SomeModel.option
ArgumentError: wrong number of arguments (given 0, expected 1)

I was dumbfounded. I was pretty sure options didn't need an argument. I double checked the class and sure enough, it didn't. option was a simple belongs_to association so there was no doubt that it didn't need an argument.

At this point, I took out my trusty source_location chops and voila:

> Somemodel.option.method(:inspect).source_location
["/Projects/app/models/option.rb", 76]

The method inspect was being overriden in the class! There are a lot of problems that can be solved with source_location so be sure to add that to your arsenal of debugging tools!

Hope you enjoyed this short but sweet post! If you need extra help handling legacy code, ask one of these Codementors to help you out!

Discover and read more posts from Eumir Gaspar
get started