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 methods inherited from class Object

or(other : T) : T | self forall T or, pipe(&) pipe

Instance Method Detail

def on(short_flag : String, long_flag : String, description : String, flag_formatter : String -> String, &block : String -> ) #

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

[View source]
def on(flag : String, description : String, *, no_help_text = false, &block : String -> ) #

[View source]