Class: Boilerpl8::CommandOptionParser
- Inherits:
-
Object
- Object
- Boilerpl8::CommandOptionParser
- Defined in:
- lib/boilerpl8.rb
Instance Attribute Summary collapse
-
#optdefs ⇒ Object
readonly
Returns the value of attribute optdefs.
Instance Method Summary collapse
-
#initialize(optdef_strs) ⇒ CommandOptionParser
constructor
A new instance of CommandOptionParser.
- #parse(args) ⇒ Object
Constructor Details
#initialize(optdef_strs) ⇒ CommandOptionParser
Returns a new instance of CommandOptionParser.
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
# File 'lib/boilerpl8.rb', line 302 def initialize(optdef_strs) @optdef_strs = optdef_strs @optdefs = [] optdef_strs.each do |optdef_str| case optdef_str when /-(\w), --(\w[-\w]*)(?:=(\S+))?\s*:\s*(\S.*)?/ ; t = [$1, $2, $3, $4] when /-(\w)(?:\s+(\S+))?\s*:\s*(\S.*)?/ ; t = [$1, nil, $2, $3] when /--(\w[-\w]*)(?:=(\S+))?\s*:\s*(\S.*)?/ ; t = [nil, $1, $2, $3] else raise "unexpected option definition: #{optdef_str}" end short, long, param, desc = t @optdefs << CommandOptionDefinition.new(short, long, param, desc) end end |
Instance Attribute Details
#optdefs ⇒ Object (readonly)
Returns the value of attribute optdefs.
318 319 320 |
# File 'lib/boilerpl8.rb', line 318 def optdefs @optdefs end |
Instance Method Details
#parse(args) ⇒ Object
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 |
# File 'lib/boilerpl8.rb', line 320 def parse(args) = {} while ! args.empty? && args[0].start_with?('-') argstr = args.shift if argstr.start_with?('--') rexp = /\A--([-\w]+)(?:=(.*))?\z/ argstr =~ rexp or err("#{argstr}: invalid option format.") name, value = $1, $2 optdef = find_by(:long, name) or err("--#{name}: unknown option.") optdef.param.nil? || value or err("#{argstr}: argument required.") optdef.param || value.nil? or err("#{argstr}: unexpected argument.") [optdef.long] = value || true else n = argstr.length i = 0 while (i += 1) < n ch = argstr[i] optdef = find_by(:short, ch) or err("-#{ch}: unknown option.") if optdef.param.nil? # no arguments [optdef.long || optdef.short] = true else # argument required param = argstr[(i+1)..-1] param = args.shift if param.empty? param or err("-#{ch}: argument required.") [optdef.long || optdef.short] = param break end end end end return end |