Class: Labrat::ArgParser

Inherits:
Object
  • Object
show all
Defined in:
lib/labrat/arg_parser.rb

Overview

An ArgParser object implements parsing of command-line arguments and gathering them into an Options object. By using the from_hash method, you can get an ArgParser object to also treat a Hash as if it were a set of command-line arguments so that config files, converted to a Hash can also be used with an ArgParser.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeArgParser

Returns a new instance of ArgParser.



12
13
14
15
16
17
18
# File 'lib/labrat/arg_parser.rb', line 12

def initialize
  @labels_seen = Set.new
  @options = Labrat::Options.new
  @parser = OptionParser.new
  @parser.summary_width = 30
  define_options
end

Instance Attribute Details

#labels_seenObject (readonly)

Returns the value of attribute labels_seen.



10
11
12
# File 'lib/labrat/arg_parser.rb', line 10

def labels_seen
  @labels_seen
end

#optionsObject (readonly)

Returns the value of attribute options.



10
11
12
# File 'lib/labrat/arg_parser.rb', line 10

def options
  @options
end

#parserObject (readonly)

Returns the value of attribute parser.



10
11
12
# File 'lib/labrat/arg_parser.rb', line 10

def parser
  @parser
end

Instance Method Details

#parse(args, prior: {}, verbose: false) ⇒ Object

Parse and set the options object to reflect the values of the given args, after merging in any prior settings into options. Return the resulting options instance. The args argument can be either a Hash or, as usual, an Array of Strings from the command-line. Throw an exception for errors encountered parsing the args.



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/labrat/arg_parser.rb', line 25

def parse(args, prior: {}, verbose: false)
  options.msg = nil
  options.verbose = verbose
  options.merge!(prior)
  case args
  when Hash
    parser.parse!(args.optionize)
  when Array
    parser.parse!(args)
  else
    raise "ArgParser cannot parse args of class '#{args.class}'"
  end
  options
rescue OptionParser::ParseError => e
  options.msg = "Error: #{e}\n\nTry `labrat --help` for usage."
  raise Labrat::OptionError, options.msg
end