Trollop: Simple Yet Powerful Command Line Option Processor

By Peter Cooper

Trollop is a command-line argument processing library for Ruby. Developer William Morgan says Trollop is "designed to provide the maximal amount of GNU-style argument processing in the minimum number of lines of code." It makes a refreshing change to the more popular, but generally scary, cmdparse. The homepage features some examples of its usage.

Once you've installed trollop with the usual gem install trollop, you could write:

require ' trollop ' opts = Trollop :: options do opt :http_1_0 , " Force HTTP/1.0 " opt :http_1_1 , " Force HTTP/1.1 " opt :hide_referer , " Hide referer ", :default => true opt :connections , " Set number of simultaneous connections ", :default => 2 end p opts

Running the script with no command line options would result in opt becoming:

{ :http_1_0= > false , :http_1_1= > false , :hide_referer= > true , :connections= > 2 , :help= > false }

You also get a --help (or -h) option for free that describes how to use the options:

Options: --http-1-0, -h: Force HTTP/1.0 --http-1-1, -t: Force HTTP/1.1 --hide-referer, -i: Hide referer (default: true) --connections, -c : Set number of simultaneous connections (default: 2) --help, -e: Show this message

Note that trollop takes care of assigning the short-hand individual letter options, assigning the next letter within the string if the previous ones are taken.

Another option is Optiflag, which present a more DSL-esque solution. Its official homepage features some compelling examples, though the simplicity of Trollop appeals to me more for some reason.

Post supported by Brightbox: Brightbox is a specialist European Rails hosting company. Each Brightbox server includes an optimised Ruby on Rails stack, SAN storage and access to a managed MySQL database cluster. They also manage dedicated clusters for large scale Rails deployments. Click here to learn more...