Menu

Published by
Categories: Ruby

I’m currently building a tool to help managing severals servers simultaneously for Softvision Media. As I decided to write the tool in Ruby, I’ve been looking for a framework to create command-line executables. On GitHub I stumbled over commander by TJ Holowaychuk of VisionMedia that provides a simple DSL for this task. It integrates with OptionParser and the Highline gem for user interaction. It automatically creates common options such as --help and --version, as well as detailed descriptions about possible commands.

A simple executable could be something like this (taken from commander’s readme):

require 'rubygems'
require 'commander'

program :name, 'Foo Bar'
program :version, '1.0.0'
program :description, 'Stupid command that prints foo or bar.'

command :foo do |c|
  c.syntax = 'foobar foo'
  c.description = 'Displays foo'
  c.when_called do |args, options|
    say 'foo'
  end
end

command :bar do |c|
  c.syntax = 'foobar bar [options]'
  c.description = 'Display bar with optional prefix and suffix'
  c.option '--prefix STRING', String, 'Adds a prefix to bar'
  c.option '--suffix STRING', String, 'Adds a suffix to bar'
  c.when_called do |args, options|
    options.default :prefix => '(', :suffix => ')'
    say "#{options.prefix}bar#{options.suffix}"
  end
end

There are still some rough edges, but in general it works pretty well.