Using Pry in your Rails application

One of the biggest challenges newbies to programming face is learning how to ask the right questions to fix problems and overcome challenges. Programming is just full of bugs and without knowing the tools that can help you overcome those challenges, bug fixing can seems like a miserable, infuriating slog.

My favorite debugging tool when working on Rails apps is Pry. It has, in a word, REVOLUTIONIZED my ability to deal with problems in the code and drill down to figure out where pain points lie. If you’re not using Pry in your Rails app, here’s how to get started:

Add Pry to your Gemfile and specify that you’ll be using it for development:

Run  bundle install

Next, move into config/environments/development.rb file within your rails app and at the bottom of the file tell your app you want to use Pry in development:

Awesome! Now that we’ve got Pry installed in our Rails app, let’s put it to work. In my example, I want to investigate why a piece of code is breaking. Based on the output I see in localhost, I know that there is something wrong with my code around user.username = in my app/models/users.rb file. Username is throwing a NoMethodError, so I’m going to place binding.pry on the line above where my code is breaking. This will spring pry into action so I can investigate that line further when I relaunch my server.

Restarting the Rails server, recreate the action that causes your program to break. In doing so, you’ll notice a couple things: 1) The site will hang 2) The console shows you that Pry is at work and you can now dig down into the broken lines of code to see what might be wrong:

Within the terminal we’re now in Pry, so just like IRB, we can begin digging into what problems lie.

In my case, I had forgotten to add Username to my User table, hence the NoMethodError. As you can see in the example above, I have since fixed it.

I’m only scratching the surface of why Pry can do. There’s a lot more information their site, along with a great introductory video that will help get you started.

About these ads

One thought on “Using Pry in your Rails application

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s