Command line options in Ruby

I was writing my WordPress theme generator last week when I stumbled upon the problem of handling command line arguments. i’ve seen it in other programs, so I know there are lots of libraries for this task.

But I didn’t need something too fancy, as Wobbie is a very simple tool — I used OptionParser.

Why is that? Mostly compatibility: it’s part of Ruby’s standard library. And it’s extremely simple to use. For example:

And it’ll generate a help automatically (with –help/-h), together with the options you created:

And creating options is pretty simple. The most important ones are true/false (on/off) switches and receiving parameters, for example regexps and directory/file names:

The idea is that each option can have a parameter after it (bower and source_dir) and you use it as you see fit, e.g. just setting a flag on the options hash or using the actual content.

I can pass the ‘my_new_theme’ directory to the program like this:

Ah, after you use the parse! method, the options are removed from the ARGV array, so you can still pass arguments without them being used by OptionParser.

There are various tools for parsing command line arguments in Ruby, Thor being my favorite. When I need something more powerful, I’ll write about it.

Leave a Reply