Method: Optimist.options

Defined in:
lib/optimist.rb

.options(args = ARGV, *a, &b) ⇒ Object

The easy, syntactic-sugary entry method into Optimist. Creates a Parser, passes the block to it, then parses args with it, handling any errors or requests for help or version information appropriately (and then exiting). Modifies args in place. Returns a hash of option values.

The block passed in should contain zero or more calls to opt (Parser#opt), zero or more calls to text (Parser#text), and probably a call to version (Parser#version).

The returned block contains a value for every option specified with opt. The value will be the value given on the commandline, or the default value if the option was not specified on the commandline. For every option specified on the commandline, a key “<option name>_given” will also be set in the hash.

Example:

require 'optimist'
opts = Optimist::options do
  opt :monkey, "Use monkey mode"                    # a flag --monkey, defaulting to false
  opt :name, "Monkey name", :type => :string        # a string --name <s>, defaulting to nil
  opt :num_limbs, "Number of limbs", :default => 4  # an integer --num-limbs <i>, defaulting to 4
end

## if called with no arguments
p opts # => {:monkey=>false, :name=>nil, :num_limbs=>4, :help=>false}

## if called with --monkey
p opts # => {:monkey=>true, :name=>nil, :num_limbs=>4, :help=>false, :monkey_given=>true}

Settings:

 Optimist::options and Optimist::Parser.new accept +settings+ to control how
 options are interpreted.  These settings are given as hash arguments, e.g:

 opts = Optimist::options(ARGV, exact_match: false) do
   opt :foobar, 'messed up'
   opt :forget, 'forget it'
 end

+settings+ include:
* :exact_match  : (default=true) Allow minimum unambigous number of characters to match a long option
* :suggestions  : (default=true) Enables suggestions when unknown arguments are given and DidYouMean is installed.  DidYouMean comes standard with Ruby 2.3+
* :implicit_short_opts : (default=true) Short options will only be created where explicitly defined.  If you do not like short-options, this will prevent having to define :short=> :none for all of your options.
Because Optimist::options uses a default argument for +args+, you must pass that argument when using the settings feature.

See more examples at www.manageiq.org/optimist



1182
1183
1184
1185
# File 'lib/optimist.rb', line 1182

def options(args = ARGV, *a, &b)
  @last_parser = Parser.new(*a, &b)
  with_standard_exception_handling(@last_parser) { @last_parser.parse args }
end