Tricks with Pry – Live Editing
When I’m programming in Ruby, one of the most indispensable tools I’ve found is an awesome little ruby gem called Pry.
Pry lets me debug my code, pausing and giving me a live REPL wherever I put a breakpoint (‘binding.pry’) in my code.
Recently, I learned about Pry’s editor integration, which gives you the ability to open your code in an external editor, make changes to it, then go back to debugging in your Pry REPL. This is super handy, because it means you don’t have to restart your Pry session every time you make a code change!
My favorite Ruby editors at the moment are RubyMine and Sublime Text. As such, I wanted to set RubyMine as my default Pry editor.
To do this, edit (or create) the “~/.pryrc” file in your home directory, and put this code in it:
1 2 3 4 5 6 7 8 9 10 |
#!/usr/bin/env ruby # Set the default Pry editor # # Example Usage: # # $ require 'active_support/all' # $ edit ActiveSupport.on_load => (open the ActiveSupport class file in the specified editor, at the line where the method is defined) # Pry.config.editor = proc { |file, line| "mine #{file}:#{line}" } |
My buddy, Jason Waldrip also came up with this nifty little addition, which will let you easily open methods in an external editor (although any changes you make won’t be live-updated in your Pry session without reloading the class files that you edited):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# Adds "rubymine", "sublime", and "vim" commands to pry, so you can quickly open the file that contains a specific method # Note: This won't work for methods are are implemented at a low-level in C, like Object.new # # Example Usage: # # $ Foo.methods(:bar).rubymine # # $ Foo.instance_methods(:bar).sublime # # $ Foo.methods(:bar).vim # [Method, UnboundMethod].each do |klass| klass.class_eval do def rubymine path = source_location.join(':') `mine #{path}` nil end def sublime path = source_location.join(':') `subl #{path}` nil end def vim path = source_location.join(':') `vim #{path}` nil end end end |
If you like this method of using Pry, have you seen this RailsConf talk about Debugger Driven Development? It’s really good.
https://www.youtube.com/watch?v=4hfMUP5iTq8