When working on a Ruby gem or a Ruby library (if you have a Ruby library, make it a gem; there is no downside, only upside), it is often desirable to have a Pry session loaded with the gem you are working on. I’ll go on a limb and say that REPL-driven development is a must-do when writing libraries. REPLs are like ice added to your beer when it isn’t cold anymore, except this ice is made from the same beer.
Many gems ship with this functionality, but if not, it is extremely easy to add one. To avoid polluting every gem with our code, we can utilize the concept of Rake’s global tasks. Rake’s default source for looking at tasks or rules is the Rakefile, and all files declared as source files in the Rakefile; are typically *.rake
files in your tasks folder, but this can vary depending on your project. However, rake also looks at ~/.rake/*.rake
if we ask it to. So let’s create a file called ~/.rake/console.rake
and add the following task to it:
1 desc "Open a pry (or irb) session preloaded with this gem"
2 task :console do
3 begin
4 require 'pry'
5 gem_name = File.basename(Dir.pwd)
6 sh %{pry -I lib -r #{gem_name}.rb}
7 rescue LoadError => _
8 sh %{irb -rubygems -I lib -r #{gem_name}.rb}
9 end
10 end
And run our shiny new rake task:
1 ➜ awesome_sauce git:(master) ✗ rake console
2 rake aborted!
3 Don't know how to build task 'console'
4
5 (See full trace by running task with --trace)
Bummer! Let’s double-check:
1 ➜ awesome_sauce git:(master) ✗ rake -T console
Nothing! What gives? Not a cause for worry because this is the expected behavior, and we have a failing test. Rake takes global pollution seriously and does not load global tasks unless asked. So let’s ask rake to do so by adding a -g
flag. Because, you know, g for global:
1 ➜ awesome_sauce git:(master) ✗ rake -gT console
2 rake console # Open a pry (or irb) session preloaded with this gem
And subsequently
1 ➜ awesome_sauce git:(master) ✗ rake -g console
2 pry -I lib -r awesome_sauce.rb
3 2.1.1 (main):0 >
4 # Just to be sure
5 2.1.1 (main):0 > ^D
6 ➜ awesome_sauce git:(master) ✗ cd ../secret_sauce
7 ➜ secret_sauce git:(hush-hush) ✗ rake -g console
8 rbx-2.1.1 (main):0 >
Happy hacking!
Edit: As Emil pointed out, pry
uses the same trick in pry --gem
1
https://github.com/pry/pry/blob/01360a684443f9e516578566afe6f41d92f63419/lib/pry/cli.rb#L209