diff --git a/lib/validates_timeliness/validations.rb b/lib/validates_timeliness/validations.rb index 7b4b902..a167e35 100644 --- a/lib/validates_timeliness/validations.rb +++ b/lib/validates_timeliness/validations.rb @@ -108,6 +108,19 @@ module ValidatesTimeliness end private + + def timeliness_restriction_value(restriction, record, type) + case restriction + when Time, Date, DateTime + restriction + when Symbol + timeliness_restriction_value(record.send(restriction), record, type) + when Proc + timeliness_restriction_value(restriction.call(record), record, type) + else + parse_date_time(restriction, type, false) + end + end # Validate value against the temporal restrictions. Restriction values # maybe of mixed type, so they are evaluated as a common type, which may @@ -128,16 +141,7 @@ module ValidatesTimeliness restriction_methods.each do |option, method| next unless restriction = configuration[option] begin - compare = case restriction - when Time, Date, DateTime - restriction - when Symbol - record.send(restriction) - when Proc - restriction.call(record) - else - parse_date_time(restriction, configuration[:type], false) - end + compare = timeliness_restriction_value(restriction, record, configuration[:type]) next if compare.nil? diff --git a/spec/validations_spec.rb b/spec/validations_spec.rb index 6d2145a..6310911 100644 --- a/spec/validations_spec.rb +++ b/spec/validations_spec.rb @@ -45,6 +45,38 @@ describe ValidatesTimeliness::Validations do ActiveRecord::Base.parse_date_time(*args) end end + + describe "timeliness_restriction_value" do + it "should return Time object when restriction is Time object" do + restriction_value(Time.now, person, :datetime).should be_kind_of(Time) + end + + it "should return Time object when restriction is string" do + restriction_value("2007-01-01 12:00", person, :datetime).should be_kind_of(Time) + end + + it "should return Time object when restriction is method symbol which returns Time object" do + person.stub!(:datetime_attr).and_return(Time.now) + restriction_value(:datetime_attr, person, :datetime).should be_kind_of(Time) + end + + it "should return Time object when restriction is method symbol which returns string" do + person.stub!(:datetime_attr).and_return("2007-01-01 12:00") + restriction_value(:datetime_attr, person, :datetime).should be_kind_of(Time) + end + + it "should return Time object when restriction is proc which returns Time object" do + restriction_value(lambda { Time.now }, person, :datetime).should be_kind_of(Time) + end + + it "should return Time object when restriction is proc which returns string" do + restriction_value(lambda {"2007-01-01 12:00"}, person, :datetime).should be_kind_of(Time) + end + + def restriction_value(*args) + ActiveRecord::Base.send(:timeliness_restriction_value, *args) + end + end describe "with no restrictions" do before :all do