module Optimist
def die(arg, msg = nil, error_code = nil)
#
# An exit code can be provide if needed
#
# Optimist::die "need at least one filename" if ARGV.empty?
#
# end
# opt :whatever # ...
# options do
#
# about -h, and die. Example:
# In the one-argument case, simply print that message, a notice
#
# die :volume, "too soft" if opts[:volume] < 0.1
# die :volume, "too loud" if opts[:volume] > 10.0
#
# end
# opt :volume, :default => 0.0
# options do
#
# 'msg', and dies. Example:
# Informs the user that their usage of 'arg' was wrong, as detailed by
def die(arg, msg = nil, error_code = nil) if @last_parser @last_parser.die arg, msg, error_code else raise ArgumentError, "Optimist::die can only be called after Optimist::options" end end
def educate
#
# end
# EOS
# where [options] are:
# #$0 [options]
# Usage:
# banner <<-EOS
# opt :volume, :default => 0.0
# options do
#
# Displays the help message and dies. Example:
def educate if @last_parser @last_parser.educate exit else raise ArgumentError, "Optimist::educate can only be called after Optimist::options" end end
def options(args = ARGV, *a, &b)
#
# p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true}
# ## if called with --monkey
#
# p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false}
# ## if called with no arguments
#
# end
# opt :num_limbs, "Number of limbs", :default => 4 # an integer --num-limbs , defaulting to 4
# opt :name, "Monkey name", :type => :string # a string --name
# opt :monkey, "Use monkey mode" # a flag --monkey, defaulting to false
# opts = Optimist::options do
# require 'optimist'
#
# Example:
#
# name>_given" will also be set in the hash.
# every option specified on the commandline, a key "
def options(args = ARGV, *a, &b) @last_parser = Parser.new(*a, &b) with_standard_exception_handling(@last_parser) { @last_parser.parse args } end
def with_standard_exception_handling(parser)
def with_standard_exception_handling(parser) yield rescue CommandlineError => e parser.die(e.message, nil, e.error_code) rescue HelpNeeded parser.educate exit rescue VersionNeeded puts parser.version exit end