class OptionParser

Overview

OptionParser is a class for command-line options processing. It supports:

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:

ext/option_parser.cr

Instance Method Summary

Instance Method Detail

def examples : String | Nil #

[View source]
def examples=(examples : String | Nil) #

[View source]
def on(flag : String, &block : String -> ) #

Allows for hiding an option from help.

Note the only difference between this and the most commonly used form of #on is that the description string is omitted.


[View source]
def to_s(io : IO) : Nil #

Returns all the setup options, formatted in a help message.


[View source]