Rails developers know and love script/console. It fires up an interactive session where you can poke around your application through the models you've built. It's invaluable for debugging and surprisingly handy for administration. But not all Ruby applications are Rails applications. Wouldn't it be nice to have a script/console anyway?
Turns out it's dead easy to build one.
First, decide which libraries and files you want loaded. This almost always includes RubyGems and some kind of boot file for your application. I usually keep mine in config/boot.rb.
Here's an example boot.rb:
require 'rubygems'
require 'hpricot'
require 'net/http'
require File.dirname(__FILE__) + '/../vendor/gems/activecouch/init'
$: << File.dirname(__FILE__) + '/../app/models'
ActiveCouch::Base.class_eval do
set_database_name 'blog'
site 'http://localhost:5984/'
end
require 'article'
require 'comment'
require 'author'
With that in place, create a Ruby script that launches IRb, requires the right files, and sets a clean prompt. I like to print a welcome banner too, because why not.
#! /usr/bin/env ruby
libs = []
libs << "irb/completion"
libs << File.dirname(__FILE__) + '/../config/boot.rb'
command_line = []
command_line << "irb"
command_line << libs.inject("") { |acc, lib| acc + %( -r "#{lib}") }
command_line << "--simple-prompt"
command = command_line.join(" ")
puts "Welcome to the console interface."
exec command
Drop that into script/console, chmod +x it, and commit. That's it — instant application console for any Ruby project.