Debugging ruby-on-rails application with pry
suggest changepry can debug a Ruby application. Adding it to a Rails app is straightforward.
Setup
To debug with pry:
- Add the gem to the
developmentandtestgroups, then runbundle install:
group :development, :test do
gem 'pry'
end
Use
Put binding.pry where execution should stop. That works in any file Ruby runs: controllers, models, and views.
- Debugging a Controller
app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
user_id = params[:id]
# Stop here to inspect the params for this action.
binding.pry
@user = User.find(user_id)
respond_to do |format|
format.html
end
end
end
The server stops in a pry console when a request hits UsersController#show. From there you can inspect params and query User.
- 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"
The server stops in pry while rendering users/show, before the response is sent. Use that stop to check @user.logged_in?.
- Debugging a Model
# app/models/user.rb
class User < ActiveRecord::Base
def full_name
binding.pry
"#{first_name} #{last_name}"
end
end
This stop runs whenever full_name is called. Pry is enough for breakpoints in controllers, views, and models. binding.pry will also stop a production process, so keep the gem out of the production group.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents