Blog Posted April 15, 2016

Using OptionParser in Rake

Problem: you'd like to leverage named arguments in your Ruby Rake task.

Solution: use OptionParser to parse the named arguments. Note the need to also call #OptionParser#order!(ARGV), which is often absent from internet documentation.

This example uses Ruby 2.2.2 and Rake 11.1.2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
require 'optparse'

task :hello do
  options = {
    name: 'world'
  }

  o = OptionParser.new

  o.banner = "Usage: rake hello [options]"
  o.on('-n NAME', '--name NAME') { |name|
    options[:name] = name
  }

  # return `ARGV` with the intended arguments
  args = o.order!(ARGV) {}

  o.parse!(args)

  puts "hello #{options[:name]}"
end

Usage:

1
2
rake hello -- --name=mike
hello mike

Default behavior with no arguments:

1
2
$ rake hello
hello world