Ruby on Rails - debugging application with pry in ruby on rails - ruby on rails tutorial - rails guides - rails tutorial - ruby rails
debugging application with pry in ruby on rails
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
- Add gem 'pry' to the application's Gemfile and bundle it
- Navigate to the application's root directory on terminal console and run 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
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
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.
iii) Debugging a Model
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.