lib/args_parser/parser.rb in args_parser-0.0.7 vs lib/args_parser/parser.rb in args_parser-0.0.8

- old
+ new

@@ -33,17 +33,26 @@ } } @aliases = {} @filter = Filter.new @validator = Validator.new - instance_eval(&block) + 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 + on_filter_error do |err, name, value| + raise err + end + on_validate_error do |err, name, value| + STDERR.puts "Error: #{err.message} (--#{name} #{value})" + exit 1 + end + + instance_eval(&block) end def arg(name, description, opts={}) params[name][:default] = opts[:default] params[name][:description] = description @@ -56,28 +65,51 @@ if block_given? @filter.add name, block end end + def on_filter_error(err=nil, name=nil, value=nil, &block) + if block_given? + @on_filter_error = block + else + @on_filter_error.call(err, name, value) if @on_filter_error + end + end + def validate(name, message, &block) if block_given? @validator.add name, message, block end end + def on_validate_error(err=nil, name=nil, value=nil, &block) + if block_given? + @on_validate_error = block + else + @on_validate_error.call(err, name, value) if @on_validate_error + end + end + def args params.keys end def parse(argv) method("parse_style_#{@config[:style]}".to_sym).call(argv) params.each do |name, param| next if [nil, true].include? param[:value] - param[:value] = @filter.filter name, param[:value] - msg = @validator.validate name, param[:value] + begin + param[:value] = @filter.filter name, param[:value] + rescue => e + on_filter_error e, name, param[:value] + end + begin + msg = @validator.validate name, param[:value] + rescue => e + on_validate_error e, name, param[:value] + end if msg - STDERR.puts "Error: #{msg} (--#{name} #{param[:value]})" - exit 1 + on_validate_error ValidationError.new(msg), name, param[:value] end end end def [](key)