diff --git a/Rakefile b/Rakefile index b30916f..fc12f29 100644 --- a/Rakefile +++ b/Rakefile @@ -3,3 +3,5 @@ require "bundler/gem_tasks" require 'rspec/core/rake_task' RSpec::Core::RakeTask.new('spec') + +task :default => :spec diff --git a/lib/yawpa.rb b/lib/yawpa.rb index 6c6ffaa..321a9f5 100644 --- a/lib/yawpa.rb +++ b/lib/yawpa.rb @@ -1,8 +1,30 @@ require "yawpa/version" +# Example options configuration: +# { +# version: {}, +# verbose: {aliases: ['-v']}, +# get: {nargs: 1}, +# set: {nargs: 2}, +# } module Yawpa + class UnknownOptionException < Exception; end + module_function - def parse(config, params) - return [[], params] + def parse(params, options) + 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 diff --git a/spec/yawpa_spec.rb b/spec/yawpa_spec.rb index 8f9e9b3..5a0ae80 100644 --- a/spec/yawpa_spec.rb +++ b/spec/yawpa_spec.rb @@ -3,11 +3,17 @@ require 'spec_helper' describe Yawpa do describe 'parse' do it "returns everything as arguments when no options present" do - config = { } + options = { } params = ['one', 'two', 'three', 'four'] - opts, args = Yawpa.parse(config, params) - opts.should eq([]) + opts, args = Yawpa.parse(params, options) + opts.should eq({}) args.should eq(params) 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