diff --git a/lib/validates_timeliness/conversion.rb b/lib/validates_timeliness/conversion.rb index 3e53bca..cf75c49 100644 --- a/lib/validates_timeliness/conversion.rb +++ b/lib/validates_timeliness/conversion.rb @@ -19,8 +19,23 @@ module ValidatesTimeliness else [0,0,0] end - dummy_date = ValidatesTimeliness.dummy_date_for_time_type - Time.local(*(dummy_date + time)) + Time.local(*(ValidatesTimeliness.dummy_date_for_time_type + time)) + end + + def evaluate_option_value(value, record) + case value + when Time, Date + value + when String + value.to_time(:local) + when Symbol + evaluate_option_value(record.send(value), record) + when Proc + result = value.arity > 0 ? value.call(record) : value.call + evaluate_option_value(result, record) + else + value + end end end diff --git a/spec/validates_timeliness/conversion_spec.rb b/spec/validates_timeliness/conversion_spec.rb index 28becd3..4370146 100644 --- a/spec/validates_timeliness/conversion_spec.rb +++ b/spec/validates_timeliness/conversion_spec.rb @@ -99,4 +99,56 @@ describe ValidatesTimeliness::Conversion do end end end + + describe "#evaluate_option_value" do + let(:person) { Person.new } + + it 'should return Date object as is' do + value = Date.new(2010,1,1) + evaluate_option_value(value, person).should == value + end + + it 'should return Time object as is' do + value = Time.mktime(2010,1,1) + evaluate_option_value(value, person).should == value + end + + it 'should return DateTime object as is' do + value = DateTime.new(2010,1,1,0,0,0) + evaluate_option_value(value, person).should == value + end + + it 'should return local Time value from string time value' do + value = '2010-01-01 12:00:00' + evaluate_option_value(value, person).should == Time.mktime(2010,1,1,12,0,0) + end + + it 'should return Time value returned from proc with 0 arity' do + value = Time.mktime(2010,1,1) + evaluate_option_value(lambda { value }, person).should == value + end + + it 'should return Time value returned by record attribute call in proc arity of 1' do + value = Time.mktime(2010,1,1) + person.birth_time = value + evaluate_option_value(lambda {|r| r.birth_time }, person).should == value + end + + it 'should return Time value from proc which returns string time' do + value = '2010-01-01 12:00:00' + evaluate_option_value(lambda { value }, person).should == Time.mktime(2010,1,1,12,0,0) + end + + it 'should return Time value for attribute method symbol which returns Time' do + value = Time.mktime(2010,1,1) + person.birth_time = value + evaluate_option_value(:birth_time, person).should == value + end + + it 'should return Time value for attribute method symbol which returns string time value' do + value = '2010-01-01 12:00:00' + person.birth_time = value + evaluate_option_value(:birth_time, person).should == Time.mktime(2010,1,1,12,0,0) + end + end end