lib/argy/parser.rb in argy-0.1.0 vs lib/argy/parser.rb in argy-0.2.0

- old
+ new

@@ -1,9 +1,10 @@ require "optparse" require "argy/help" require "argy/option" require "argy/argument" +require "argy/options" module Argy class Parser attr_reader :examples, :arguments, :options, :flags @@ -50,63 +51,64 @@ def help(**opts) Help.new(self, **opts) end def default_values - (arguments + options).reduce(unused_arguments: []) do |acc, opt| + parameters.reduce(unused_args: []) do |acc, opt| acc[opt.name] = opt.default acc end end - def parse(argv) + def parse(argv, strategy: nil) argv = argv.dup values = default_values - parser = build_parser(values) - parser.parse!(argv) + case strategy + when :order + parser.order!(argv) + when :permute + parser.permute!(argv) + else + parser.parse!(argv) + end + populate_arguments(values, argv) - validate!(values) + Options.new validate!(values) + rescue OptionParser::ParseError => error + raise ParseError.new(error) + end + def validate!(values) + parameters.each do |param| + param.validate(values[param.name]) + end values - rescue OptionParser::MissingArgument => error - raise MissingArgumentError, error.message end private def populate_arguments(values, argv) argv.zip(arguments).each do |value, arg| if arg.nil? - values[:unused_arguments] << value + values[:unused_args] << value else values[arg.name] = arg.coerce(value) end end end - def validate!(values) - parameters.each do |param| - param.validate(values[param.name]) - end - end - def build_parser(values) OptionParser.new do |o| options.each do |opt| o.on(*opt.to_option_parser) do |value| values[opt.name] = opt.coerce(value) end end flags.each do |flag, action| o.on(*flag, &action) - end - - o.on("-h", "--help") do - puts help - exit end end end end end