Menu

Pry reload!

29 September 2014

One thing I always liked about RoR development is being able to reload model code without needing to restart rails c by way of using the reload! method from within rails console. I was wondering if there was any way to port this method over to pry and gem development.

Setup

The setup is rather simple and can be applied to IRB as well as pry. This blog post will focus on pry however.

Within your gem directory, edit your Rakefile to include the following code:

To see how this works, let's dive into how this is accomplished. At the core of it, the implementation of reload! is relying on just one global variable, $LOADED_FEATURES.

This global variable is an array that is added to every time an object is required within the pry, or irb session. Since the gem is automatically required when the pry session starts, it is included with $LOADED_FEATURES when the initial session starts. This is accomplished by the following annotated code:

task :console do
require 'pry' # loads pry when the rake task is called
require 'gem_name' # loads your gem within pry after it starts
...
end

The reload! method is equally as simple:

def reload!
# Change 'gem_name' here too:
# iterate over the $LOADED_FEATURES array and select only those
# who are within the path of your gem
files = $LOADED_FEATURES.select { |feat| feat =~ /\/gem_name\// }
# after it builds the correct array, it will load the file once more into
# the current irb / pry session
files.each { |file| load file }
end