Class: ClOptions
- Inherits:
-
Object
- Object
- ClOptions
- Defined in:
- lib/cloptions.rb
Instance Method Summary collapse
- #handle(args) ⇒ Object
- #handle_options(name, value) ⇒ 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 @options = end |
Instance Method Details
#handle(args) ⇒ Object
50 51 52 53 54 55 56 57 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 |
# File 'lib/cloptions.rb', line 50 def handle(args) @args = [ ] i = 0 while i < args.length arg = args[i] if arg == '--' @args.concat args[i+1...args.length] break elsif m = arg.match(/\A--([a-z]+(-[a-z]+)*)/) long_name, option_value = parse_longname(arg, m) next_captured = false # next argument may be options argument if (option_value == nil) && (i+1 < args.length) option_value = args[i+1] next_captured = true end took_value = long_name, option_value i += 1 if took_value && next_captured elsif arg[0] == '-' short_name, option_value = parse_shortname(arg) next_captured = false # next argument may be options argument if (option_value == nil) && (i+1 < args.length) option_value = args[i+1] next_captured = true end took_value = short_name, option_value i += 1 if took_value && next_captured else @args << arg end i += 1 end @args end |
#handle_options(name, value) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/cloptions.rb', line 7 def (name, value) puts "inside handle_options, name is " + name.to_s + ", value is " + value.to_s took_value = false valid = false @options.each{|option| if (option[:long_name] == name) || (option[:short_name] == name) valid = true if (option[:takes_value]) && (value == nil) raise "option " + name + " requires value" break elsif option[:takes_value] @obj.send(option[:method], value) took_value = true else @obj.send(option[:method]) end break end } raise "Invalid option: " + name if !valid took_value end |
#parse_longname(arg, m) ⇒ Object
30 31 32 33 34 35 36 37 |
# File 'lib/cloptions.rb', line 30 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
39 40 41 42 43 44 45 46 47 48 |
# File 'lib/cloptions.rb', line 39 def parse_shortname (arg) short_name = arg[1] option_value = nil if arg[2] == '=' option_value = arg[3...arg.length] elsif arg.length > 2 short_name = arg[1...arg.length] end return short_name, option_value end |