Class: GLI::GLIOptionBlockParser

Inherits:
Object
  • Object
show all
Defined in:
lib/gli/gli_option_block_parser.rb

Overview

An “option block” is a set of parseable options, starting from the beginning of the argument list, stopping with the first unknown command-line element. This class handles parsing that block

Direct Known Subclasses

CommandOptionBlockParser

Instance Method Summary collapse

Constructor Details

#initialize(option_parser_factory, exception_klass_or_block) ⇒ GLIOptionBlockParser

Create the parser using the given OptionParser instance and exception handling strategy.

option_parser_factory

An OptionParserFactory instance, configured to parse wherever you are on the command line

exception_klass_or_block

means of handling exceptions from OptionParser. One of:

an exception class

will be raised on errors with a message

lambda/block

will be called with a single argument - the error message.



14
15
16
17
18
19
20
21
22
23
24
# File 'lib/gli/gli_option_block_parser.rb', line 14

def initialize(option_parser_factory,exception_klass_or_block)
  @option_parser_factory = option_parser_factory
  @extra_error_context = nil
  @exception_handler = if exception_klass_or_block.kind_of?(Class)
                         lambda { |message,extra_error_context|
                           raise exception_klass_or_block,message
                         }
                       else
                         exception_klass_or_block
                       end
end

Instance Method Details

#parse!(args) ⇒ Object

Parse the given argument list, returning the unparsed arguments and options hash of parsed arguments. Exceptions from OptionParser are given to the handler configured in the constructor

args

argument list. This will be mutated

Returns unparsed args



32
33
34
35
36
37
38
# File 'lib/gli/gli_option_block_parser.rb', line 32

def parse!(args)
  do_parse(args)
rescue OptionParser::InvalidOption => ex
  @exception_handler.call("Unknown option #{ex.args.join(' ')}",@extra_error_context)
rescue OptionParser::InvalidArgument => ex
  @exception_handler.call("#{ex.reason}: #{ex.args.join(' ')}",@extra_error_context)
end