lib/args_parser/parser.rb in args_parser-0.0.4 vs lib/args_parser/parser.rb in args_parser-0.0.5

- old
+ new

@@ -1,9 +1,11 @@ module ArgsParser def self.parse(argv=[], &block) - Parser.new(argv, &block) + parser = Parser.new(&block) + parser.parse argv + parser end class Parser attr_reader :first @@ -24,26 +26,45 @@ def aliases @aliases ||= Hash.new end public - def initialize(argv=[], &block) + def initialize(&block) unless block_given? raise ArgumentError, 'initialize block was not given' end + @filter = Filter.new + @validator = Validator.new instance_eval(&block) - parse argv + filter do |v| + (v.kind_of? String and v =~ /^\d+$/) ? v.to_i : v + end + filter do |v| + (v.kind_of? String and v =~ /^\d+\.\d+$/) ? v.to_f : v + end end def arg(name, description, opts={}) params[name][:default] = opts[:default] params[name][:description] = description params[name][:index] = params.keys.size params[name][:alias] = opts[:alias] aliases[opts[:alias]] = name if opts[:alias] end + def filter(name=nil, &block) + if block_given? + @filter.add name, block + end + end + + def validate(name, message, &block) + if block_given? + @validator.add name, message, block + end + end + def args params.keys end def parse(argv) @@ -60,11 +81,15 @@ if arg =~ /^-+[^-\s]+$/ params[k][:value] = true k = arg.scan(/^-+([^-\s]+)$/)[0][0].strip.to_sym k = aliases[k] if aliases[k] else - arg = arg.to_i if arg =~ /^\d+$/ - arg = arg.to_f if arg =~ /^\d+\.\d+$/ + arg = @filter.filter k, arg + msg = @validator.validate k, arg + if msg + STDERR.puts "Error: #{msg} (--#{k} #{arg})" + exit 1 + end params[k][:value] = arg k = nil end end end