Options are defined using the #opt
or #option
methods. They can then be used from the command line with a short and/or long name. For instance
opt :v, :version
Creates an Option which can be used with -v
or --version
. Options should also be given a description so you know what they do! You can either pass a string with the description to #opt(ion)
;
opt :v, :version, 'Display current version'
or call #desc
before defining the Option,
desc 'Display current version'
opt :v, :version
Options with names containing underscores are callable with dashes replacing the underscores, as well as with underscores.
opt :longer_than_expected
# can use --longer-than-expected
# and --longer_than_expected
Options can be passed a block when defined. The block is then executed when the Option is used.
opt :hello do
puts 'Hello'
end
They can also be given arguments (read the Arguments section for more details).
opt :hello, arg: '<name>' do |name|
puts "Hello #{name}"
end
The arguments are then passed to the block. It's possible to have multiple arguments, including optional arguments.
opt :hello, arg: '<first> [<last>]' do |first, last|
puts ["Hello", first, last].compact.join(' ')
end
# --hello John
#=> "Hello John"
# --hello John Doe
#=> "Hello John Doe"
If an expected argument is not given an error is raised detailing the problem. Using the previous example,
$ clive_test --hello
Clive::Parser::MissingArgumentError: missing
argument for --hello, found [], needed
<first> [<last>]