I don’t write CLI applications often enough, but when I do, I like to use the Trollop gem.

Here’s a simple tutorial on how to use it. We’ll go with the most basic usage on this post.

A simple example

Say we want to create a script to publish a blog post from the terminal (we’ll just fake the actual work for this example).

We need to pass some data in order to create it:

  • The post title, which is a string
  • A flag denoting if it’s a draft
  • The post ID, in case it exists on the server, which is an integer

This is quite easy

require 'trollop'
require 'awesome_print'

opts = Trollop::options do
  opt :title, "Post title", type: :string
  opt :draft, "Create as a draft", short: :r
  opt :post_id, "Post id", type: :integer
end

ap opts

When we run this, we get:

$ ruby post --title="Trollop" -r true
{
          :title => "Trollop",
          :draft => true,
        :post_id => nil,
           :help => false,
    :title_given => true,
    :draft_given => true
}

So, we have a Hash extracted from the ARGV Array.

We have our title string, our draft boolean and our post id, which is nil because we didn’t provide one. We could set a default value by passing the :default parameter.

opt :post_id, "Post id", type: :integer, default: 0

And now we see zero as the value for post_id

$ ruby post --title="Trollop" -r true
{
          :title => "Trollop",
          :draft => true,
        :post_id => 0,
           :help => false,
    :title_given => true,
    :draft_given => true
}

Flags

Flags get a special treatment, lets see a simpler example

require 'trollop'
require 'awesome_print'

opts = Trollop::options do
  opt :draft, "Create as a draft", short: :r
end

ap opts[:draft]

We can use the --draft option to set the draft flag to true.
But for forcing it to false, we can pass in the --no-draft option.

$ ruby post
false
$ ruby post --draft
true
$ ruby post --no-draft
false

Up to here we have the basic usage down. But there’s one other topic I’d like to show you

Help

Going back to our original example, we can pass the --help or -h flag and trollop will make sure to show us all the options we can pass in

ruby post --help
Options:
  -t, --title=<s>      Post title
  -r, --draft          Create as a draft
  -p, --post-id=<i>    Post id
  -h, --help           Show this message

Neat, right?

If you need to create a quick script with more than one option, using trollop is a great choice.

See you on the next one.

Saluti.