Tuesday, March 13, 2012

Debugging Ruby on Rails on Mac OS X

If you have installed the latest version of Ruby (1.9.3 p125 as of 3/13/2012) on Mac OS X and need to debug a Rails application you will find little out-of-the-box support. In this entry I enumerate the steps required to enable debugging and illustrate how to invoke the debugger.

Note: The default version of Ruby on Mac OS X Lion (10.7.3) is 1.8.7. For many this is a significant drawback as many of the language enhancements in 1.9.x cannot be leveraged. This article assumes you have already installed the newer version. If that's not the case, you will find details instructions here.

Alright, to the important stuff now. The first step is to apply the debug patch to your current installation of Ruby.

$ rvm reinstall 1.9.3-p125 --patch debug --force-autoconf  

Now edit the Gemfile in  your Rails application and add the following lines.

gem 'ruby-debug19', :require => false
gem 'ruby-debug-base19', :git => 'https://github.com/tribune/ruby-debug-base19.git', :require => false

Now run bundle config:

$ bundle config build.ruby-debug-base19 --with-ruby-include=$rvm_path/src/ruby-1.9.3-p125/

We are not done yet. Next we need to install linecache19 as follows:

$ gem install linecache19

Finally, we do:

$ bundle install

Now we should be ready to debug our Rails application.  The first step is to bootstrap the debugger in the application. This is achieved by including the following directive in the source code:

def some_function
  debugger
  ...
  respond_to do [format]
  ...
  end
end 

Then, launch your application with the debugger option

 $ rails s --debugger

At this point the execution of the thread on which you placed in the [debugger] directive should break, and you should be able to invoke the debugger commands. A description of the debugger commands can be found here.

Happy debugging.

No comments:

Post a Comment