raise exception on unknown option

This commit is contained in:
Josh Holtrop 2013-01-20 22:28:36 -05:00
parent b2b0d90c4d
commit 56e644e16e
3 changed files with 35 additions and 5 deletions

View File

@ -3,3 +3,5 @@ require "bundler/gem_tasks"
require 'rspec/core/rake_task' require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new('spec') RSpec::Core::RakeTask.new('spec')
task :default => :spec

View File

@ -1,8 +1,30 @@
require "yawpa/version" require "yawpa/version"
# Example options configuration:
# {
# version: {},
# verbose: {aliases: ['-v']},
# get: {nargs: 1},
# set: {nargs: 2},
# }
module Yawpa module Yawpa
class UnknownOptionException < Exception; end
module_function module_function
def parse(config, params) def parse(params, options)
return [[], params] opts = {}
args = []
i = 0
while i < params.length
param = params[i]
if param[0] != '-'
args << params[i]
else
opt_config = options[param] || options[param.to_sym]
raise UnknownOptionException.new("Unknown option '#{param}'") if opt_config.nil?
end
i += 1
end
return [opts, args]
end end
end end

View File

@ -3,11 +3,17 @@ require 'spec_helper'
describe Yawpa do describe Yawpa do
describe 'parse' do describe 'parse' do
it "returns everything as arguments when no options present" do it "returns everything as arguments when no options present" do
config = { } options = { }
params = ['one', 'two', 'three', 'four'] params = ['one', 'two', 'three', 'four']
opts, args = Yawpa.parse(config, params) opts, args = Yawpa.parse(params, options)
opts.should eq([]) opts.should eq({})
args.should eq(params) args.should eq(params)
end end
it "raises an exception when an invalid option is passed" do
options = { }
params = ['one', '--option', 'two']
expect { Yawpa.parse(params, options) }.to raise_error
end
end end
end end