We love command line interfaces. We’ve written before about how we use the Tumblr gem to post to this site. If you want to add a nice CLI to your Ruby app, Joshua Hull from the Padrino team has released Optitron, an easy way to support option and command parsing.

Install the gem

gem install optitron

A quick example

@parser = Optitron.new {
  opt 'verbose', "Be very loud"
  cmd "install", "This installs things" do
    arg "file", "The file to install"
  end
  cmd "show", "This shows things" do
    arg "first", "The first thing to show"
    arg "second", "The second optional thing to show", :required => false
  end
  cmd "kill", "This kills things" do
    opt "pids", "A list of pids to kill", :type => :array
    opt "pid", "A pid to kill", :type => :numeric
    opt "names", "Some sort of hash", :type => :hash
  end
  cmd "join", "This joins things" do
    arg "thing", "Stuff to join", :type => :greedy
  end
}

Then you can print those options with @parser.help:

Commands

show [first] <second>          # This shows things
install [file]                 # This installs things
kill                           # This kills things
  -p/--pids=[ARRAY]            # A list of pids to kill
  -P/--pid=[NUMERIC]           # A pid to kill
  -n/--names=[HASH]            # Some sort of hash
join [thing1 thing2 ...]       # This joins things

Global options

-v/--verbose                   # Be very loud

Let’s see how Optitron parses inbound arguments

response = @parser.parse(%w(-v install file))
response.command
=> "install"
response.args
=> ["file"]
response.params
=> {"verbose" => true}

With four patch releases today, this gem is moving fast but one to keep an eye on.

[Source on GitHub]


Have comments? Send a tweet to @TheChangelog on Twitter.

Subscribe to The Changelog Weekly – our weekly email covering everything that hits our open source radar.