This post will be a little less coherent than some of the others, but I wanted to write down a few things I’ve found to be very helpful when trying to debug my Ruby code.
Quickly find syntax errors
A surprising number of people don’t know that you can run ruby with -c
from the command line to learn about syntax errors. Let’s say I have a simple Dog
class with an unclosed string.
1 2 3 4 5 6 7 8 9 10 11 |
|
This is a trivial example, but if I was having trouble tracking down the problem I’d do something like this:
1 2 3 |
|
Inspecting instance variables
From the console, we have the power to reach inside an object and see its instance variables even if there are no getter and setter methods defined on the object.
1 2 3 4 5 6 7 |
|
This slightly different syntax also works
1 2 |
|
If we’re not sure what state the object is holding on to, we can get a list of all the defined instance variables using #instance_variables
.
1 2 |
|
Calling private methods
If you want to call a private method from the command line, you can do so with #send
.
1 2 3 4 5 6 |
|
Discover where a method was defined
Sometimes, especially when working on a big application with other people, it’s tricky to learn where a particular method is defined. This is especially true when classes are being extended by gems that you did not write or install yourself.
To track those down, you can do this in the console.
1
|
|
For example, I might do something like this:
1 2 |
|
If the cache
method had been overridden, as it sometimes is by gems like dalli_store
, I would see a reference to that gem instead of rails.