Hi, I'm Benedikt Deicke, and I'm a freelance web and software developer. I'm mainly building user focused web applications using Ruby on Rails and JavaScript. Additionally I'm currently studying for my master's degree and enjoying photography in my spare time. Feel free to get in touch with me, I'm available for hire!

March 19th, 2009
Commander: command-line executables in 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):

   1  require 'rubygems'
   2  require 'commander'
   3  
   4  program :name, 'Foo Bar'
   5  program :version, '1.0.0'
   6  program :description, 'Stupid command that prints foo or bar.'
   7  
   8  command :foo do |c|
   9    c.syntax = 'foobar foo'
  10    c.description = 'Displays foo'
  11    c.when_called do |args, options|
  12      say 'foo'
  13    end
  14  end
  15  
  16  command :bar do |c|
  17    c.syntax = 'foobar bar [options]'
  18    c.description = 'Display bar with optional prefix and suffix'
  19    c.option '--prefix STRING', String, 'Adds a prefix to bar'
  20    c.option '--suffix STRING', String, 'Adds a suffix to bar'
  21    c.when_called do |args, options|
  22      options.default :prefix => '(', :suffix => ')'
  23      say "#{options.prefix}bar#{options.suffix}"
  24    end
  25  end

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

Posted by benediktFiled in Ruby
Bookmark and Share

Leave a comment