As Rails developers, it is imperative that we be comfortable and productive in the console. The console is where we have the shortest feedback cycles, making it perfect for learning and tinkering. The Rails console is useful in debugging code, manipulating local data, and trying out new ideas and implementations.
However, once we emerge from the weeds and start working on more involved problems, the console’s blade begins to lose its sharpness. Fortunately, we can blend the instantaneous feedback of the console with the structure and organization of Ruby objects/methods by using a scratchpad file.
A scratchpad is a file that is loaded automatically onto all Rails console sessions.
I recommend using Pry (pry-rails) as a console. Pry automatically loads a file named .pryrc
in the app’s root (and also in ~/.pryrc
) whenever a console is launched (rails console
or binding.pry
). We can use that file to load our scratchpad.
First, create a scratch.rb file in the Rails root directory (touch scratch.rb
). Then load the scratchpad file scratch.rb
in the .pryrc
:
Here is a basic scratch file with an example:
module Scratch
def scratch!
load __FILE__
end
def my_scratch_method
puts "my_scratch_method was called"
end
def my_user
User.find_by(email: "my@email.com")
end
end
include Scratch
The Scratch module loads in scratch.rb
and is included into the Pry console session, meaning that all methods defined within it are now available in the console.
Note that I have added a #scratch!
method to the module which reloads the file to the latest saved version without having to reload the entire console. This allows you to change code in the Scratch
module and receive feedback in real time by chaining #scratch!
:
scratch!; my_scratch_method
Another handy use for the scratch file is to add commonly used helper methods that don’t belong in the source code. For example, I keep a progress bar setup handy:
require 'ruby-progressbar'
module Scratch
def each_with_progress_bar(scope, &block)
progress_bar = ProgressBar.create
progress = progress_bar(scope.count)scope.find_each do |item|
block.call(item).tap do
progress.increment
end
end
end
...
end
module Scratch
There are a bunch of interesting use cases for having a scratchpad file available in the console. If you have an interesting one, drop me a comment. I’d love to learn how others use scratchpads.
I learned this trick from my co-worker, friend, and walking vim encyclopedia Scott Pierce (@ddrscott).