class OptionParser
- OptionParser
- Reference
- Object
Overview
OptionParser
is a class for command-line options processing. It supports:
- Short and long modifier style options (example:
-h
,--help
) - Passing arguments to the flags (example:
-f filename.txt
) - Subcommands
- Automatic help message generation
Run crystal
for an example of a CLI built with OptionParser
.
NOTE To use OptionParser
, you must explicitly import it with require "option_parser"
Short example:
require "option_parser"
upcase = false
destination = "World"
OptionParser.parse do |parser|
parser.banner = "Usage: salute [arguments]"
parser.on("-u", "--upcase", "Upcases the salute") { upcase = true }
parser.on("-t NAME", "--to=NAME", "Specifies the name to salute") { |name| destination = name }
parser.on("-h", "--help", "Show this help") do
puts parser
exit
end
parser.invalid_option do |flag|
STDERR.puts "ERROR: #{flag} is not a valid option."
STDERR.puts parser
exit(1)
end
end
destination = destination.upcase if upcase
puts "Hello #{destination}!"
Subcommands
OptionParser
also supports subcommands.
Short example:
require "option_parser"
verbose = false
salute = false
welcome = false
name = "World"
parser = OptionParser.new do |parser|
parser.banner = "Usage: example [subcommand] [arguments]"
parser.on("salute", "Salute a name") do
salute = true
parser.banner = "Usage: example salute [arguments]"
parser.on("-t NAME", "--to=NAME", "Specify the name to salute") { |_name| name = _name }
end
parser.on("welcome", "Print a greeting message") do
welcome = true
parser.banner = "Usage: example welcome"
end
parser.on("-v", "--verbose", "Enabled verbose output") { verbose = true }
parser.on("-h", "--help", "Show this help") do
puts parser
exit
end
end
parser.parse
if salute
STDERR.puts "Saluting #{name}" if verbose
puts "Hello #{name}"
elsif welcome
STDERR.puts "Welcoming #{name}" if verbose
puts "Welcome!"
else
puts parser
exit(1)
end
Defined in:
option_parser.crConstructors
-
.parse(args = ARGV, *, gnu_optional_args : Bool = false, &) : self
Creates a new parser, with its configuration specified in the block, and uses it to parse the passed args (defaults to
ARGV
).
Constructor Detail
Creates a new parser, with its configuration specified in the block,
and uses it to parse the passed args (defaults to ARGV
).
Refer to #gnu_optional_args?
for the behaviour of the named parameter.