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

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ Parser



21
22
23
24
25
26
27
28
29
# File 'lib/optio/parser.rb', line 21

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



57
58
59
# File 'lib/optio/parser.rb', line 57

def banner(text)
  @banner = text
end

#parse(args = ARGV) ⇒ Object



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

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

#parse!(args = ARGV) ⇒ Object



67
68
69
70
71
# File 'lib/optio/parser.rb', line 67

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)


47
48
49
50
# File 'lib/optio/parser.rb', line 47

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



42
43
44
# File 'lib/optio/parser.rb', line 42

def switch(switch_name, opts = {})
  store_parameter(switch_name, opts, @switches)
end