Paluy on Miscellaneous

Of course I'm an optimist - I don't see much point in being anything else. - Winston Churchill

Debugging Rails Application - Part 1

How to debug Rails application?

There are several gems to debug your Ruby code:

debugger - A fork of ruby-debug that works on Ruby 1.9.3

Install (rvm):

1
gem install debugger -- --with-ruby-include=$rvm_path/src/ruby-1.9.3-p374/
Gemfile
1
2
3
  group :development, :test do
    gem 'debugger'
  end

Usage:

1
2
  # Wherever you need a debugger, simply add:
  require 'debugger'; debugger

pry-debugger - Using debugger within pry

Gemfile
1
2
3
  group :development, :test do
    gem 'pry-debugger'
  end

Configuration (Optional):

Add aliases:

$HOME/.pryrc
1
2
3
4
  Pry.commands.alias_command 'con', 'continue'
  Pry.commands.alias_command 's', 'step'
  Pry.commands.alias_command 'n', 'next'
  Pry.commands.alias_command 'fin', 'finish'

NOTE: You won’t be able to use those words as params while debugging

Usage:

1
2
  # Wherever you need a debugger, simply add:
  binding.pry

Example:

home_controller.rb
1
2
3
4
5
6
7
8
9
  class HomeController < ApplicationController
    def index
      # Some code ...

      binding.pry
      # Code to debug
      # ...
    end
  end

Now start your rails server (rails s) and visit your controller url: http://localhost:3000/home. The pry debugger console will appear in your terminal. You can use all pry functionality inside your application in addition to predefined aliases(next, step, continue, etc.).

Other useful commands:

  • help - show a list of available commands
  • exit - exit a context with a user provided value
  • whereami - describe the current location (alternative: $)
  • break - set a breakpoint
  • wtf -v - see the entire backtrace

Comments