implement :boolean option flag

This commit is contained in:
Josh Holtrop 2014-06-25 15:05:19 -04:00
parent f74253844b
commit a78ee7275e
2 changed files with 32 additions and 3 deletions

View File

@ -73,12 +73,22 @@ module Yawpa
param = params[i]
if param =~ /^--([^=]+)(?:=(.+))?$/
param_name, val = $1, $2
bool_val = true
if options[param_name].nil?
raise ArgumentParsingException.new("Unknown option '#{param_name}'")
if param_name =~ /^no(.*)$/
test_param_name = $1
if options[test_param_name]
param_name = test_param_name
bool_val = false
end
end
end
opt_config = options[param_name]
raise ArgumentParsingException.new("Unknown option '#{param_name}'") unless opt_config
param_key = opt_config[:key]
if opt_config[:nargs].last == 0
if opt_config[:boolean]
opts[param_key] = bool_val
elsif opt_config[:nargs].last == 0
opts[param_key] = true
else
opts[param_key] = []
@ -155,6 +165,7 @@ module Yawpa
nargs = (nargs..nargs) if nargs.is_a?(Fixnum)
newopts[newkey][:nargs] = nargs
newopts[newkey][:short] = v[:short] || ''
newopts[newkey][:boolean] = v[:boolean]
end
end
end

View File

@ -1,7 +1,7 @@
require 'spec_helper'
describe Yawpa do
describe 'parse' do
describe ".parse" do
it "returns everything as arguments when no options present" do
options = { }
params = ['one', 'two', 'three', 'four']
@ -213,5 +213,23 @@ describe Yawpa do
expect(opts[:two]).to be_falsey
expect(args).to eq(['arg', '--two'])
end
it "supports :boolean option flag" do
options = {
push: {boolean: true},
}
opts, args = Yawpa.parse(%w[hi], options)
expect(opts).to eq({})
expect(args).to eq(%w[hi])
opts, args = Yawpa.parse(%w[--push one two], options)
expect(opts).to eq(push: true)
expect(args).to eq(%w[one two])
opts, args = Yawpa.parse(%w[arg --nopush], options)
expect(opts).to eq(push: false)
expect(args).to eq(%w[arg])
end
end
end