rails debugging trick

Lately, I’ve been spending some time in Rails. As you know, no code is 100% bug-free … in most cases, you can figure out errors/bugs by checking the log files, present in your log directory or by checking the traceback.

What do you do when you need to step through your code? I searched for some solutions on the internet, and I asked on stackoverflow. I didn’t receive any answers to my question, but, I remembered a gem I was using in my ruby code: ruby-debug. This gem allows you to stop your script at a given moment and step through the rest of the code.

I’m sure most/all of you know how to install a gem. If not, here’s the command:

gem install ruby-debug

After you install the gem, you include it in your code like this :

require "rubygems"
require "ruby-debug"

You need the require “rubygems” line if you install the gem through ruby’s gem management system. After you included the gem in your source file, you can place “debugger calls” inside your code, like this:

def my_method
    if some_condition?

When the ruby interpreter reaches the debugger line, you’ll be dropped to a irb-like shell, from where you can step through your code and inspect your variables. A small catch: the shell you get back isn’t a full-featured REPL. If for example, you write the name of a variable and expect it’s value to be printed, it’s not gonna happen. The gem treats it like a command, so, you need to say p name_of_variable or puts name_of_variable .

I suggest you take out those “debugger” lines after you’re done debugging.

If you know of other solutions to this type of problem, please mention them in a comment.


2 Responses to “rails debugging trick”

  1. 1 Chris
    May 1, 2009 at 22:09

    You don’t have to include ‘ruby-debugger’ everytime. Just start script/server –debugger.

    Further have a look at: http://guides.rubyonrails.org/debugging_rails_applications.html

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog Stats

  • 221,399 hits

%d bloggers like this: