Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
simple-option-parser
$ ruby complex.rb -h
Usage: complex.rb [options]
Specific options:
-z, --zero ZERO Enforce argument ZERO
-o, --one ONE Require argument ONE
-t, --two [TWO] This is a multi-line description for
option TWO
-r, --three THREE Float argument THREE
-f, --four FOUR List of arguments for argument FOUR: [:a, :b, :c]
$ ruby complex.rb
ERROR: Missing input for argument zero
$ ruby complex.rb --zero ZERO
{:two=>"optional", :three=>1.1, :zero=>"ZERO"}
$ ruby complex.rb --zero ZERO --four WRONG
invalid argument: --four WRONG
$ ruby complex.rb --zero ZERO --four a
{:two=>"optional", :three=>1.1, :zero=>"ZERO", :four=>:a}
require 'optparse'
class Parser
REQUIRED_PARAMETERS = [:zero]
VALID_PARAMETERS = {
four: [:a, :b, :c]
}
def self.parse!
Parser.new.parse!
end
def parse!
options = parse_input(default)
validate!(options)
options
rescue => e
puts e.message
exit
end
private
def validate!(options)
REQUIRED_PARAMETERS.each { |opt| fail "ERROR: Missing input for argument #{opt}" if options[opt].nil? }
end
def parse_input(default)
options = default
OptionParser.new do |opts|
opts.banner = 'Usage: complex.rb [options]'
opts.separator ''
opts.separator 'Specific options:'
# Enforced argument
opts.on('-z', '--zero ZERO',
'Enforce argument ZERO') do |zero|
options[:zero] = zero
end
# Mandatory argument, as in, if you use -o you must provide an argument.
# It does not mean you must use -o
opts.on('-o', '--one ONE',
'Require argument ONE') do |one|
options[:one] = one
end
# Optional argument; multi-line description.
opts.on('-t', '--two [TWO]',
'This is a multi-line description for',
' option TWO') do |two|
options[:two] = two
end
# Cast to Float; No long-name.
opts.on('-r', '--three THREE', Float, 'Float argument THREE') do |three|
options[:three] = three
end
# Limited selection.
opts.on('-f', '--four FOUR',
VALID_PARAMETERS[:four],
"List of arguments for argument FOUR: #{VALID_PARAMETERS[:four]}") do |four|
options[:four] = four
end
end.parse!
options
end
def default
{
two: 'optional',
three: 1.1
}
end
end
puts Parser.parse!
$ ruby sample.rb -h
Usage: simple.rb [options]
-v, --[no-]verbose Run verbosely
$ ruby sample.rb -v
{verbose: true}
$ ruby sample.rb --no-verbose
{verbose: false}
require 'optparse'
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: simple.rb [options]"
opts.on("-v", "--[no-]verbose", "Run verbosely") do |v|
options[:verbose] = v
end
end.parse!
puts options
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment