Hello all you party people! This article will show you how you can easily debug your Rails code.
If you’re using the default Rails Rack server, Webrick – the best debugging tool I’ve been able to find out there is pry. Its use is pretty straightforward:

First off you’d need to add the pry gem to your Gemfile. Since this is used for development purposes, it should be added in the :development group:

group :development, :test do
 .......
 gem 'pry'
end

Next we’d need to update our bundle:

$ bundle

After that’s done, all that’s left to do is to actually use the gem’s functionality in our code. Basically, this will be of use whenever one of your actions crashes and you can’t figure out straight away what caused it to crash. All you need to do is invoke binding.pry somewhere in your code – which will create a Pry session at the point it’s called. This will pretty much open a ‘developer console’ where you can play around with all the objects that have been defined up until you called binding.pry. You can then easily debug your action, like you’d regularly do in an irb console. When you’re done with the Pry session the program will resume.

Here’s how this would work in a regular create action from a Users controller:

def create
  user = User.create(user_params)
  binding.pry #Start a pry session to see if the new user looks the way we want
  if user.save
     flash.now[:success] = "Welcome"
     sign_in user
     redirect_to user
  else
     flash.now[:error] = "Something went wrong: #{user.errors.full_messages}"
     render 'new'
  end
end

Voila! After you run the create action – you should view the Pry session in the console, where your rails server is running.

If you are using a zero-config Rack server, like Pow (which I personally love), you would pretty much need a way to start Pry remotely. There’s a gem for that as well, called Pry-Remote, which works pretty much the same way. The only difference is that we need to invoke binding.remote_pry instead of binding.pry. Easy peasy. Here’s how the same code from before would look like in this scenario:

 def show
   binding.remote_pry
   @groups = current_user.groups
 end

Now, all that’s left is to run the pry-remote command to start your pry session after the action has been called:

 

Happy debugging.