Skip to content

Commit

Permalink
Fix before_type_cast for non-dirty attributes (issue adzap#52).
Browse files Browse the repository at this point in the history
Only use before_type_cast implementation if earlier than 3.1.0 which has
it's own working version for date/time fields now.
  • Loading branch information
adzap committed Sep 21, 2011
1 parent 34824bb commit 86b7bc4
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 7 deletions.
2 changes: 1 addition & 1 deletion lib/validates_timeliness/attribute_methods.rb
Expand Up @@ -46,7 +46,7 @@ def #{attr_name}=(value)
def define_timeliness_before_type_cast_method(attr_name)
method_body, line = <<-EOV, __LINE__ + 1
def #{attr_name}_before_type_cast
_timeliness_raw_value_for('#{attr_name}')
_timeliness_raw_value_for('#{attr_name}') || @attributes['#{attr_name}']
end
EOV
generated_timeliness_methods.module_eval(method_body, __FILE__, line)
Expand Down
3 changes: 2 additions & 1 deletion lib/validates_timeliness/orm/active_record.rb
Expand Up @@ -7,7 +7,8 @@ module ClassMethods
def define_attribute_methods
super
# Define write method and before_type_cast method
define_timeliness_methods(true)
use_before_type_cast = ::ActiveRecord::VERSION::STRING < '3.1.0'
define_timeliness_methods(use_before_type_cast)
end

def timeliness_attribute_timezone_aware?(attr_name)
Expand Down
8 changes: 3 additions & 5 deletions spec/spec_helper.rb
Expand Up @@ -71,9 +71,10 @@ class PersonWithShim < Person
end

class Employee < ActiveRecord::Base
define_attribute_methods

attr_accessor :redefined_birth_date_called
validates_date :birth_date, :allow_nil => true
validates_date :birth_time, :allow_nil => true
validates_date :birth_datetime, :allow_nil => true

def birth_date=(value)
self.redefined_birth_date_called = true
Expand All @@ -90,8 +91,5 @@ def birth_date=(value)
Person.reset_callbacks(:validate)
PersonWithShim.timeliness_validated_attributes = []
Person._validators.clear
Employee.reset_callbacks(:validate)
Employee.timeliness_validated_attributes = []
Employee._validators.clear
end
end
10 changes: 10 additions & 0 deletions spec/validates_timeliness/orm/active_record_spec.rb
Expand Up @@ -82,6 +82,7 @@ class EmployeeWithParser < ActiveRecord::Base
r = Employee.create!
r.birth_date = '2010-01-01'
r.reload

r._timeliness_raw_value_for(:birth_date).should be_nil
end
end
Expand All @@ -94,7 +95,16 @@ class EmployeeWithParser < ActiveRecord::Base
it 'should return original value' do
r = Employee.new
r.birth_datetime = date_string = '2010-01-01'

r.birth_datetime_before_type_cast.should == date_string
end

it 'should return attribute if no attribute assignment has been made' do
datetime = Time.zone.local(2010,01,01)
Employee.create(:birth_datetime => datetime)

r = Employee.last
r.birth_datetime_before_type_cast.should match(/2010-01-01 00:00:00/)
end
end
end

0 comments on commit 86b7bc4

Please sign in to comment.