Andrew Andrew - 11 months ago 51
Ruby Question

How to use Pry with Sinatra?

I am writing my first Sinatra application and would like to use Pry to inspect/debug some things going on in the application. I haven't used Pry before either, but I would like to try it out. How would I get started using Pry with my Sinatra application?

Answer Source


  1. Use require 'pry' at the top of your application.
  2. Call binding.pry in your code whenever you want to drop into the interactive session. For information on using Pry, see Turning IRB on its head with Pry and the Pry wiki.
  3. When you are done with a particular interactive session, type exit or Ctrl-D; Sinatra will resume running where it left off.


require 'sinatra'
require 'pry'

get '/' do
  @cats = rand(100)
  html = haml :index

  <head><title>Hello World</title></head>
    %p I have #{@cats} cat#{:s unless @cats==1}!

Here's what it looks like when I start the web server:

C:\>ruby pry_into_sinatra.rb
== Sinatra/1.2.6 has taken the stage on 4567 for development with backup from Thin
>> Thin web server (v1.2.11 codename Bat-Shit Crazy)
>> Maximum connections set to 1024
>> Listening on, CTRL+C to stop

When I make a request in a web browser to http://localhost:4567 the console drops into the Pry debugger before sending the result:

From: pry_into_sinatra.rb @ line 7 in Sinatra::Application#HEAD /:

     2: require 'pry'
     4: get '/' do
     5:         @cats = rand(100)
     6:         html = haml :index
 =>  7:         binding.pry
     8:         html
     9: end
    11: __END__
    12: @@index
pry(#<Sinatra::Application:0x3300ac8>)> @cats
=> 42
pry(#<Sinatra::Application:0x3300ac8>)> puts html
  <head><title>Hello World</title></head>
    <p>I have 42 cats!</p>
=> nil
pry(#<Sinatra::Application:0x3300ac8>)> exit - - [24/Aug/2011 13:25:57] "GET / HTTP/1.1" 200 96 28.5390 - - [24/Aug/2011 13:25:57] "GET /favicon.ico HTTP/1.1" 404 447 0.0010

Further Debugging

If you want to be able to use traditional debugging commands, such as setting line-based breakpoints, or stepping, or breaking when exceptions are raised, see the PryDebug library by Mon-Ouie.