script/console for your application

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.

Leave feedback...

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.