Class: ClOptions
- Inherits:
-
Object
- Object
- ClOptions
- Defined in:
- lib/cloptions.rb
Instance Method Summary collapse
- #handle(args) ⇒ Object
- #handle_option(type, name, attached, nextarg) ⇒ Object
-
#initialize(obj, options) ⇒ ClOptions
constructor
A new instance of ClOptions.
- #parse_longname(arg, m) ⇒ Object
- #parse_shortname(arg) ⇒ Object
Constructor Details
#initialize(obj, options) ⇒ ClOptions
Returns a new instance of ClOptions.
2 3 4 5 |
# File 'lib/cloptions.rb', line 2 def initialize(obj, ) @obj = obj = end |
Instance Method Details
#handle(args) ⇒ Object
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 |
# File 'lib/cloptions.rb', line 58 def handle(args) @args = [ ] i = 0 while i < args.length arg = args[i] found = nil if arg.class != String @args.concat args[i...args.length] break elsif arg == '--' @args.concat args[i+1...args.length] break elsif m = arg.match(/\A--([a-z]+(-[a-z]+)*)/) name, attached = parse_longname(arg, m) found = :long_name elsif arg[0] == '-' name, attached = parse_shortname(arg) found = :short_name else @args.concat args[i...args.length] break end if found next_arg = (i+1 < args.length) ? args[i+1] : nil begin need_shift = handle_option found, name, attached, next_arg if need_shift.class == String errmsg = need_shift return errmsg + ": " + arg.to_s end end i += 1 if need_shift == true end i += 1 end @args end |
#handle_option(type, name, attached, nextarg) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/cloptions.rb', line 7 def handle_option(type, name, attached, nextarg) need_shift = false valid_option = false value = attached.nil? ? nextarg : attached .each { |option| if option[type] == name valid_option = true if option[:takes_value] need_shift = attached.nil? if value @obj.send(option[:method], value) else return "value required for option" end else if attached.nil? @obj.send(option[:method]) else return "Invalid option" end end break end } return "Invalid option" unless valid_option need_shift end |
#parse_longname(arg, m) ⇒ Object
35 36 37 38 39 40 41 42 |
# File 'lib/cloptions.rb', line 35 def parse_longname(arg, m) long_name = arg[m.begin(1)...m.end(1)] option_value = nil if arg[m.end(1)] == '=' option_value = arg[m.end(1)+1...arg.length] end return long_name, option_value end |
#parse_shortname(arg) ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/cloptions.rb', line 44 def parse_shortname (arg) short_name = if arg.length > 1 arg[1] else raise "no option given" end option_value = if arg.length > 2 arg[2...arg.length] else nil end return short_name, option_value end |