Class Cri::OptionParser
In: lib/cri/option_parser.rb
Parent: Object

Cri::OptionParser is used for parsing commandline options.

Methods

parse  

Classes and Modules

Class Cri::OptionParser::IllegalOptionError
Class Cri::OptionParser::OptionRequiresAnArgumentError

Public Class methods

Parses the commandline arguments in arguments_and_options, using the commandline option definitions in definitions.

arguments_and_options is an array of commandline arguments and options. This will usually be ARGV.

definitions contains a list of hashes defining which options are allowed and how they will be handled. Such a hash has three keys:

:short:The short name of the option, e.g. a. Do not include the ’-’ prefix.
:long:The long name of the option, e.g. all. Do not include the ’—’ prefix.
:argument:Whether this option‘s argument is required (:required), optional (:optional) or forbidden (:forbidden).

A sample array of definition hashes could look like this:

    [
      { :short => 'a', :long => 'all',  :argument => :forbidden },
      { :short => 'p', :long => 'port', :argument => :required  },
    ]

During parsing, two errors can be raised:

IllegalOptionError:An unrecognised option was encountered, i.e. an option that is not present in the list of option definitions.
OptionRequiresAnArgumentError:An option was found that did not have a value, even though this value was required.

What will be returned, is a hash with two keys, :arguments and :options. The :arguments value contains a list of arguments, and the :options value contains a hash with key-value pairs for each option. Options without values will have a nil value instead.

For example, the following commandline options (which should not be passed as a string, but as an array of strings):

    foo -xyz -a hiss -s -m please --level 50 --father=ani -n luke squeak

with the following option definitions:

    [
      { :short => 'x', :long => 'xxx',    :argument => :forbidden },
      { :short => 'y', :long => 'yyy',    :argument => :forbidden },
      { :short => 'z', :long => 'zzz',    :argument => :forbidden },
      { :short => 'a', :long => 'all',    :argument => :forbidden },
      { :short => 's', :long => 'stuff',  :argument => :optional  },
      { :short => 'm', :long => 'more',   :argument => :optional  },
      { :short => 'l', :long => 'level',  :argument => :required  },
      { :short => 'f', :long => 'father', :argument => :required  },
      { :short => 'n', :long => 'name',   :argument => :required  }
    ]

will be translated into:

    {
      :arguments => [ 'foo', 'hiss', 'squeak' ],
      :options => {
        :xxx    => true,
        :yyy    => true,
        :zzz    => true,
        :all    => true,
        :stuff  => true,
        :more   => 'please',
        :level  => '50',
        :father => 'ani',
        :name   => 'luke'
      }
    }

[Validate]