From 2822e368e3c3c766896e408e6c6a660ab4cdc828 Mon Sep 17 00:00:00 2001 From: Adam Meehan Date: Thu, 24 Feb 2011 07:58:48 +1100 Subject: [PATCH] Exit restriction validation on first restriction error --- lib/validates_timeliness/validator.rb | 13 ++++++++++--- spec/validates_timeliness/validator_spec.rb | 9 ++++++++- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/lib/validates_timeliness/validator.rb b/lib/validates_timeliness/validator.rb index f413bab..9ae70d7 100644 --- a/lib/validates_timeliness/validator.rb +++ b/lib/validates_timeliness/validator.rb @@ -20,6 +20,8 @@ module ValidatesTimeliness :datetime => '%Y-%m-%d %H:%M:%S' }.freeze + RESTRICTION_ERROR_MESSAGE = "Error occurred validating %s for %s restriction:\n%s" + def self.kind :timeliness end @@ -45,17 +47,22 @@ module ValidatesTimeliness value = parse(raw_value) if value.is_a?(String) || options[:format] value = type_cast_value(value, @type) - return add_error(record, attr_name, :"invalid_#{@type}") if value.blank? + add_error(record, attr_name, :"invalid_#{@type}") and return if value.blank? + validate_restrictions(record, attr_name, value) + end + + def validate_restrictions(record, attr_name, value) @restrictions_to_check.each do |restriction| begin restriction_value = type_cast_value(evaluate_option_value(options[restriction], record), @type) unless value.send(RESTRICTIONS[restriction], restriction_value) - return add_error(record, attr_name, restriction, restriction_value) + add_error(record, attr_name, restriction, restriction_value) and break end rescue => e unless ValidatesTimeliness.ignore_restriction_errors - add_error(record, attr_name, "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}") + message = RESTRICTION_ERROR_MESSAGE % [ attr_name, restriction.inspect, e.message ] + add_error(record, attr_name, message) and break end end end diff --git a/spec/validates_timeliness/validator_spec.rb b/spec/validates_timeliness/validator_spec.rb index 8a6cbab..d1ab227 100644 --- a/spec/validates_timeliness/validator_spec.rb +++ b/spec/validates_timeliness/validator_spec.rb @@ -136,7 +136,7 @@ describe ValidatesTimeliness::Validator do let(:person) { Person.new(:birth_date => Date.today) } before do - Person.validates_time :birth_date, :is_at => lambda { raise } + Person.validates_time :birth_date, :is_at => lambda { raise }, :before => lambda { raise } end it "should be added when ignore_restriction_errors is false" do @@ -152,6 +152,13 @@ describe ValidatesTimeliness::Validator do person.errors[:birth_date].should be_empty end end + + it 'should exit on first error' do + with_config(:ignore_restriction_errors, false) do + person.valid? + person.errors[:birth_date].should have(1).items + end + end end describe "#format_error_value" do