From 6acf61aa88dfcd3ab9262e0b0d206c1f60c582f7 Mon Sep 17 00:00:00 2001 From: Adam Meehan Date: Sun, 1 Aug 2010 23:26:23 +1000 Subject: [PATCH] ignore restriction value errors --- lib/validates_timeliness.rb | 3 +++ lib/validates_timeliness/validator.rb | 12 ++++++++--- spec/validates_timeliness/validator_spec.rb | 24 +++++++++++++++++++++ 3 files changed, 36 insertions(+), 3 deletions(-) diff --git a/lib/validates_timeliness.rb b/lib/validates_timeliness.rb index 5e01986..84c1d1a 100644 --- a/lib/validates_timeliness.rb +++ b/lib/validates_timeliness.rb @@ -18,6 +18,9 @@ module ValidatesTimeliness mattr_accessor :dummy_date_for_time_type @@dummy_date_for_time_type = [ 2000, 1, 1 ] + # Ignore errors when restriction options are evaluated + mattr_accessor :ignore_restriction_errors + @@ignore_restriction_errors = false end require 'validates_timeliness/conversion' diff --git a/lib/validates_timeliness/validator.rb b/lib/validates_timeliness/validator.rb index 945a4f6..7045de3 100644 --- a/lib/validates_timeliness/validator.rb +++ b/lib/validates_timeliness/validator.rb @@ -39,9 +39,15 @@ module ValidatesTimeliness value = type_cast(value) (RESTRICTIONS.keys & options.keys).each do |restriction| - restriction_value = type_cast(evaluate_option_value(options[restriction], record)) - unless value.send(RESTRICTIONS[restriction], restriction_value) - return record.errors.add(attr_name, restriction, :restriction => restriction_value) + begin + restriction_value = type_cast(evaluate_option_value(options[restriction], record)) + unless value.send(RESTRICTIONS[restriction], restriction_value) + return record.errors.add(attr_name, restriction, :restriction => restriction_value) + end + rescue => e + unless ValidatesTimeliness.ignore_restriction_errors + record.errors[attr_name] = "Error occurred validating #{attr_name} for #{restriction.inspect} restriction:\n#{e.message}" + end end end end diff --git a/spec/validates_timeliness/validator_spec.rb b/spec/validates_timeliness/validator_spec.rb index fa20ffe..1bb9966 100644 --- a/spec/validates_timeliness/validator_spec.rb +++ b/spec/validates_timeliness/validator_spec.rb @@ -66,4 +66,28 @@ describe ValidatesTimeliness::Validator do end end end + + describe "restriction value errors" do + let(:person) { Person.new(:birth_date => Date.today) } + + before do + Person.validates_time :birth_date, :is_at => lambda { raise } + end + + it "should be added when ignore_restriction_errors is false" do + ValidatesTimeliness.ignore_restriction_errors = false + person.valid? + person.errors[:birth_date].first.should match("Error occurred validating birth_date for :is_at restriction") + end + + it "should not be added when ignore_restriction_errors is true" do + ValidatesTimeliness.ignore_restriction_errors = true + person.valid? + person.errors[:birth_date].should be_empty + end + + after :all do + ValidatesTimeliness.ignore_restriction_errors = false + end + end end