Rails coders will be more than familiar with the script/console command. It fires up a session in which you can interact with your application through the models that you've built. It's invaluable for debugging problems and can be really useful when building or administering the application. Not all of our Ruby applications are Rails applications though. Wouldn't it be nice to have a script/console anyway?

Turns out it's really easy to build one. Here's how.

First, decide on the libraries and files you'd like to have loaded. This almost always includes RubyGems and an init file from your application. I usually store the init file in config/boot.rb.

An example boot.rb could look something like this:

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'

Once we have these files we can create a Ruby script that'll run IRb, require the files, and set the prompt to something nice and simple. I also like to print out a welcome banner.

#! /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 <APPLICATION NAME> console interface."
exec command

I'd usually whack that code in script/console, make it chmod +x and commit it to the source code repository. Bam, instant application console.

written by
Craig
published
2009-01-25
Disagree? Found a typo? Got a question?
If you'd like to have a conversation about this post, email craig@barkingiguana.com. I don't bite.
You can verify that I've written this post by following the verification instructions:
curl -LO http://barkingiguana.com/2009/01/25/scriptconsole-for-your-application.html.orig
curl -LO http://barkingiguana.com/2009/01/25/scriptconsole-for-your-application.html.orig.asc
gpg --verify scriptconsole-for-your-application.html.orig{.asc,}