class Optio::Parser
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
Public Class Methods
new() { |self| ... }
click to toggle source
# File lib/optio/parser.rb, line 24 def initialize(&block) @switches = {} @subcommands = {} @banner = nil @parsed_params = {} if block_given? yield self end end
Public Instance Methods
parse(args = ARGV)
click to toggle source
# 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)
click to toggle source
# 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)
click to toggle source
TODO support sub commands
# 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 = {})
click to toggle source
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
-
# 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
Private Instance Methods
rb_parser(parsed_params)
click to toggle source
# File lib/optio/parser.rb, line 79 def rb_parser(parsed_params) OptionParser.new do |rb_parser| @switches.each do |switch_name, switch_obj| rb_parser.banner = @banner if @banner rb_parser.on(*(switch_obj.rb_parser_args)) do |param| parsed_params[switch_name] = param end end end end
store_parameter(parameter, opts, mapping)
click to toggle source
# File lib/optio/parser.rb, line 90 def store_parameter(parameter, opts, mapping) unless parameter.is_a?(Symbol) || parameter.is_a?(String) raise ArgumentError, "parameter #{parameter} must be of types Atom or String" end parameter_sym = parameter.to_sym if mapping.has_key?(parameter_sym) raise Exceptions::SwitchAlreadyExistsError, "parameter #{parameter} already been defined" end mapping[parameter_sym] = opts end