Class: PmgmtLib::OptionsParser
- Inherits:
-
Object
- Object
- PmgmtLib::OptionsParser
- Defined in:
- lib/optionsparser.rb
Overview
Allows parsing of command line options without requiring any subclassing.
Instance Attribute Summary collapse
-
#opts ⇒ Object
readonly
Returns the value of attribute opts.
-
#remaining ⇒ Object
readonly
Returns the value of attribute remaining.
Instance Method Summary collapse
- #add_option(option, assign, help) ⇒ Object
- #add_typed_option(option, type, assign, help) ⇒ Object
- #add_validator(fn) ⇒ Object
-
#initialize(command_name, args) ⇒ OptionsParser
constructor
A new instance of OptionsParser.
- #parse ⇒ Object
- #validate ⇒ Object
Constructor Details
#initialize(command_name, args) ⇒ OptionsParser
Returns a new instance of OptionsParser.
21 22 23 24 25 26 |
# File 'lib/optionsparser.rb', line 21 def initialize(command_name, args) @opts = OpenStruct.new @parser = create_parser(command_name) @args = args @validators = [] end |
Instance Attribute Details
#opts ⇒ Object (readonly)
Returns the value of attribute opts.
19 20 21 |
# File 'lib/optionsparser.rb', line 19 def opts @opts end |
#remaining ⇒ Object (readonly)
Returns the value of attribute remaining.
19 20 21 |
# File 'lib/optionsparser.rb', line 19 def remaining @remaining end |
Instance Method Details
#add_option(option, assign, help) ⇒ Object
28 29 30 31 |
# File 'lib/optionsparser.rb', line 28 def add_option(option, assign, help) @parser.on(option, help) {|v| assign.call(@opts, v)} self end |
#add_typed_option(option, type, assign, help) ⇒ Object
33 34 35 36 |
# File 'lib/optionsparser.rb', line 33 def add_typed_option(option, type, assign, help) @parser.on(option, type, help) {|v| assign.call(@opts, v)} self end |
#add_validator(fn) ⇒ Object
38 39 40 41 |
# File 'lib/optionsparser.rb', line 38 def add_validator(fn) @validators.push(fn) self end |
#parse ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/optionsparser.rb', line 43 def parse() begin @remaining = @parser.parse @args rescue ArgumentError => e STDERR.puts e STDERR.puts STDERR.puts @parser.help exit 1 end self end |
#validate ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 |
# File 'lib/optionsparser.rb', line 55 def validate() @validators.each do |fn| begin fn.call(@opts) rescue ArgumentError => e STDERR.puts e STDERR.puts STDERR.puts @parser.help exit 1 end end self end |