How to add interactive console to your Ruby app?
I’ve been writing some Ruby app lately (the kind that runs in the terminal and doesn’t include
Webrick as http server) and I found myself missing some of the tooling that is available with Rails - especially the command line.
The ability to just type rails c
and play around with your code was one of the framework killer-features
back in the days:
Here’s how to do it in Ruby console application :)
Sample application
Our app will contain only three files
# cat.rb
class Cat
def make_sound
puts 'miau'
end
end
# config/application.rb
require_relative '../cat'
# main.rb
require_relative 'config/application'
Cat.new.make_sound
Console script
We will follow Rails conventions and put our executables in the bin
directory
# bin/console
#!/usr/bin/env ruby
require 'irb'
require 'irb/completion'
require_relative '../config/application'
IRB.start
And that’s it - we can now type bin/console
and our Cat
class is available!
Reloading code
It wouldn’t feel like a real console without being able to call reload!
so let’s try to add it!
First we need to change require
to load
in application.rb
because the former will not load
our source file again if it has been already loaded.
# config/application.rb
load File.expand_path('../../cat.rb', __FILE__)
And then we will add reload!
function to our script:
# bin/console
#!/usr/bin/env ruby
require 'irb'
require 'irb/completion'
def reload!
load File.expand_path('../../config/application.rb', __FILE__)
end
reload!
IRB.start