Customizing Pry

Pry is a popular alternative to the standard IRB shell for Ruby. It has some really useful features such as syntax highlighting and being able to view, browse and modify source code within a REPL session. It is especially popular in Rails since it allows you to debug code interactively - I use it most often when I’m trying to understand test failures.

One feature that I was unaware of is that you can customize Pry. From the Pry wiki:

The .pryrc file is analogous to the .irbrc file for IRB. You can use the .pryrc file to customize Pry.

When pry starts, it checks for a .pryrc file in your home directory(~/.pryrc) and also for a per-project .pryrc in the current directory(./.pryrc). Both files are used if they exist, with the file from your home directory being loaded first.

I don’t spend an enormous amount of time in Pry, but one annoying scenario I keep running into is that I’ll be interacting with a variable that is an HTML response. For example, I might have a test that makes a web request and the response is simply the standard Rails error page HTML. It’s really difficult to see the actual problem in the console, but it’s really easy to see in a browser.

Pry Session

I basically either want to take this output and get it into the clipboard - so I can search through it in Vim - or I want to just view it in a browser. You can do both of these by adding custom commands to your .pryrc file.

Pry.config.commands.command 'pbcopy', 'Copy input to clipboard' do |input|
  input = input ? target.eval(input) : _pry_.last_result
  IO.popen('pbcopy', 'w') { |io| io << input }
end

Pry.config.commands.command 'html-view', 'Write input to and html file and open it' do |input|
  input = input ? target.eval(input) : _pry_.last_result

  require 'tempfile'
  file = Tempfile.new(['pry-result', '.html'])
  begin
    file.write(input)
    file.rewind
    `open #{file.path}`
  ensure
    file.unlink
  end
end

If you run html-view response.body the response will be opened by your default browser. If you don’t pass a variable the last result will be used.

You can also configure things like the Pry prompt, but I haven’t really found the need for this.