pry is a powerful tool that can be used to debug any ruby application. Setting up a ruby-on-rails application with this gem is very easy and straightforward.
Setup
To start debugging your application with pry
gem 'pry'
to the application's Gemfile
and bundle itgroup :development, :test do
gem 'pry'
end
bundle install
. You're all set to start using it anywhere on your application.Use
Using pry in your application is just including binding.pry
on the breakpoints you want to inspect while debugging. You can add binding.pry
breakpoints anywhere in your application that is interpreted by ruby interpreter (any app/controllers, app/models, app/views files)
i) Debugging a Controller
app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
use_id = params[:id]
// breakpoint to inspect if the action is receiving param as expected
binding.pry
@user = User.find(user_id)
respond_to do |format|
format.html
end
end
end
In this example, the rails server pauses with a pry console at the break-point when you try to visit a page routing to show
action on UsersController
. You can inspect params
object and make ActiveRecord query on User
model from that breakpoint
ii) Debugging a View
app/views/users/show.html.haml
%table
%tbody
%tr
%td ID
%td= @user.id
%tr
%td email
%td= @user.email
%tr
%td logged in ?
%td
- binding.pry
- if @user.logged_in?
%p= "Logged in"
- else
%p= "Logged out"
In this example, the break-point pauses with pry console when the users/show
page is pre-compiled in the rails server before sending it back to the client's browser. This break-point allows to debug correctness of @user.logged_in?
when it is misbehaving.
ii) Debugging a Model
app/models/user.rb
class User < ActiveRecord::Base
def full_name
binding.pry
"#{self.first_name} #{self.last_name}"
end
end
In this example, the break-point can be used to debug User
model's instance method full_name
when this method is called from anywhere in the application.
In conclusion, pry is a powerful debugging tool for rails application with easy setup and straightforward debugging guideline. Give this a try.