module Argos
Constants
- VERSION
Public Instance Methods
Called when an option that takes an argument occurs at the end of the argv list, with no argument following it.
# File lib/argos.rb 12 def argument_missing opt 13 raise OptionError, "#{opt}: no argument provided." 14 end
# File lib/argos.rb 16 def handle opt, handler, *args # :nodoc 17 args.empty? ? handler[] : handler[args[0]] 18 rescue => ex 19 raise OptionError, "#{opt}: #{ex}" 20 end
Returns the hash of parsed options and argument values. The argv
array is modified: every recognized option and argument is deleted.
The optdef
hash defines the options and their arguments.
Each key is an option name (without “-” chars).
The value for a key in optdef
is used to generate the value for the same key in the options hash returned by this method.
If the value has an arity method and arity > 0, the value is considered to be a handler; it is called with the argument string to return the value associated with the option in the hash returned by the method.
If the arity <= 0, the value is considered to be a handler for an option without arguments; it is called with no arguments to return the value of the option.
If there is no arity method, the object itself is used as the value of the option.
Only one kind of input will cause an exception (not counting exceptions raised by handler code or by bugs):
-
An option is found at the end of the list, and it requires an argument. This results in a call to
argument_missing
, which by default raisesOptionError
.
# File lib/argos.rb 51 def parse_options argv, optdef 52 orig = argv.dup; argv.clear 53 opts = {} 54 55 loop do 56 case (argstr=orig.shift) 57 when nil, "--" 58 argv.concat orig 59 break 60 61 when /^(--)([^=]+)=(.*)/, /^(-)([^-])(.+)/ 62 short = ($1 == "-"); opt = $2; arg = $3 63 unless optdef.key?(opt) 64 argv << argstr 65 next 66 end 67 handler = optdef[opt] 68 arity = (handler.arity rescue nil) 69 opts[opt] = 70 case arity 71 when nil; orig.unshift("-#{arg}") if short; handler 72 when 0,-1; orig.unshift("-#{arg}") if short; handle(opt, handler) 73 else handle(opt, handler, arg) 74 end 75 76 when /^--(.+)/, /^-(.)$/ 77 opt = $1 78 unless optdef.key?(opt) 79 argv << argstr 80 next 81 end 82 handler = optdef[opt] 83 arity = (handler.arity rescue nil) 84 opts[opt] = 85 case arity 86 when nil; handler 87 when 0,-1; handle(opt, handler) 88 else handle(opt, handler, orig.shift || argument_missing(opt)) 89 end 90 91 else 92 argv << argstr 93 end 94 end 95 96 opts 97 end