Module: OptionParserGenerator
- Defined in:
- lib/optsparser_generator.rb
Overview
Small lib for generating an OptionParser from an OpenStruct
Defined Under Namespace
Classes: OptionCollision, WrongArgumentType
Constant Summary collapse
- SPECIAL_POSTFIXES =
Special postfixes for Hash keys
[ '--class', '--help', '--proc', '--required', '--short', '--values', ].freeze
Class Method Summary collapse
-
.[](ostruct, **options) ⇒ Object
Does the magic.
-
.parse(ostruct, argv, **opt) ⇒ OpenStruct
Shorthand when parsing is only needed once.
-
.parse!(ostruct, argv = ARGV, **opt) ⇒ OpenStruct
Same as parse, removes parsed elements from argv.
Class Method Details
.[](ostruct, **options) ⇒ Object
TODO:
write documentation :(
TODO:
split this up
Does the magic
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 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/optsparser_generator.rb', line 60 def self.[](ostruct, **) defaults = handle_arguments(ostruct) optparser = OptionParser.new do |opts| opts.instance_variable_set(:@required, {}) defaults.each_pair do |key, val| trigger = key.to_s.tr('_', '-') next if trigger.end_with?(*SPECIAL_POSTFIXES) arguments = generate_arguments(defaults, key, val) case val when FalseClass, TrueClass uneven_no = /\Ano(-no-no)*-(?!no)/ =~ trigger if trigger.start_with?('no-') trigger.gsub!(/\A(no-)+/, '') # removes no- prefixes check_collisions(trigger, key, defaults) unless [:ignore_collisions] end arguments.unshift "--[no-]#{trigger}" block = lambda do |bool| # inverted when it starts with no_ bool ^ uneven_no end else klass = val.class klass = val.is_a?(Integer) ? Integer : klass klass = defaults.special_value(key, 'class') || klass arguments.push klass values = defaults.special_value(key, 'values') arguments.push values if values arguments.unshift "--#{trigger}=ARG" block = lambda do |str| str end end if (proc = defaults.special_value(key, 'proc')) block = proc end opts.on(*arguments) do |arg| opts.instance_variable_get(:@required)[key] = true opts.instance_variable_get(:@out)[key] = block.call(arg) end if defaults.special_value(key, 'required') opts.instance_variable_get(:@required)[key] = false end end unless [:generate_no_help] opts.on('-h', '--help') do puts opts exit end end end # add default values optparser.instance_variable_set(:@defaults, defaults) optparser.extend(OptParsePatch) end |
.parse(ostruct, argv, **opt) ⇒ OpenStruct
Shorthand when parsing is only needed once.
Generates an OptionParser and calls parse on it
173 174 175 |
# File 'lib/optsparser_generator.rb', line 173 def self.parse(ostruct, argv, **opt) self[ostruct, **opt].parse(argv) end |
.parse!(ostruct, argv = ARGV, **opt) ⇒ OpenStruct
Same as parse, removes parsed elements from argv
180 181 182 |
# File 'lib/optsparser_generator.rb', line 180 def self.parse!(ostruct, argv = ARGV, **opt) self[ostruct, **opt].parse!(argv) end |