Class: Optio::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/optio/parser.rb

Overview

A wrapper class for Ruby’s OptionParser Usage:

p = Optio::Parser.new do |parser|
  parser.switch :verbose, short: 'v', desc: 'Verbose logging', type: TrueClass
end
p.parse! # or p.parse!(ARGV) or p.parse!(args_array)

By default the arguments that are parsed are the ones in ARGV

TODO

Implement support for sub commands;

Optio::Parser.new do |parser|
  parser.subcommand :dance
end

TODO expose the option to auto assign short switch

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Parser

Returns a new instance of Parser.



24
25
26
27
28
29
30
31
32
# File 'lib/optio/parser.rb', line 24

def initialize(&block)
  @switches = {}
  @subcommands = {}
  @banner = nil
  @parsed_params = {}
  if block_given?
    yield self
  end
end

Instance Method Details

Setup the banner for the option parser

Parameters:

text

Banner text



61
62
63
# File 'lib/optio/parser.rb', line 61

def banner(text)
  @banner = text
end

#parse(args = ARGV) ⇒ Object



65
66
67
68
69
# File 'lib/optio/parser.rb', line 65

def parse(args = ARGV)
  parsed_params = {}
  rb_parser(parsed_params).parse(args)
  parsed_params
end

#parse!(args = ARGV) ⇒ Object



71
72
73
74
75
# File 'lib/optio/parser.rb', line 71

def parse!(args = ARGV)
  parsed_params = {}
  rb_parser(parsed_params).parse!(args)
  parsed_params
end

#subcommand(subcommand, opts) ⇒ Object

TODO support sub commands

Raises:

  • (NotImplementedError)


51
52
53
54
# File 'lib/optio/parser.rb', line 51

def subcommand(subcommand, opts)
  store_parameter(subcommand, opts, @subcommands)
  raise NotImplementedError, 'support for sub commands is not yet supported'
end

#switch(switch_name, opts = {}) ⇒ Object

Define a switch

Parameters:

switch_name

The name of the switch, i.e. the string that will represent the switch :someswitch will be parsed as --someswitch

opts

Additional options for the switch;

  • :desc - The description that will be shown for the switch.

  • :type - Expected argument type, see OptionParser for details

  • :short: - The short switch, i,e -h for --help



45
46
47
48
# File 'lib/optio/parser.rb', line 45

def switch(switch_name, opts = {})
  switch_obj = Switch.new(switch_name, opts)
  store_parameter(switch_name, switch_obj, @switches)
end