1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Make before_type_cast available for datetime fields

[#3973 state:committed]

Signed-off-by: Santiago Pastorino <santiago@wyeworks.com>
This commit is contained in:
Akira Matsuda 2010-12-16 18:31:31 +09:00 committed by Santiago Pastorino
parent ed2eb6fa87
commit 817e370136
2 changed files with 19 additions and 19 deletions

View file

@ -40,12 +40,13 @@ module ActiveRecord
def define_method_attribute=(attr_name)
if create_time_zone_conversion_attribute?(attr_name, columns_hash[attr_name])
method_body, line = <<-EOV, __LINE__ + 1
def #{attr_name}=(time)
def #{attr_name}=(original_time)
time = original_time.dup
unless time.acts_like?(:time)
time = time.is_a?(String) ? Time.zone.parse(time) : time.to_time rescue time
end
time = time.in_time_zone rescue nil if time
write_attribute(:#{attr_name}, time)
write_attribute(:#{attr_name}, (time || original_time))
end
EOV
generated_attribute_methods.module_eval(method_body, __FILE__, line)

View file

@ -116,24 +116,23 @@ class AttributeMethodsTest < ActiveRecord::TestCase
end
end
unless current_adapter?(:Mysql2Adapter)
def test_read_attributes_before_type_cast_on_datetime
developer = Developer.find(:first)
# Oracle adapter returns Time before type cast
unless current_adapter?(:OracleAdapter)
assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s
else
assert_equal developer.created_at.to_s(:db) , developer.attributes_before_type_cast["created_at"].to_s(:db)
developer.created_at = "345643456"
assert_equal developer.created_at_before_type_cast, "345643456"
assert_equal developer.created_at, nil
developer.created_at = "2010-03-21 21:23:32"
assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32"
assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32")
end
def test_read_attributes_before_type_cast_on_datetime
developer = Developer.find(:first)
if current_adapter?(:Mysql2Adapter)
# Mysql2 keeps the value in Time instance
assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s(:db)
else
assert_equal developer.created_at.to_s(:db), developer.attributes_before_type_cast["created_at"].to_s
end
developer.created_at = "345643456"
assert_equal developer.created_at_before_type_cast, "345643456"
assert_equal developer.created_at, nil
developer.created_at = "2010-03-21 21:23:32"
assert_equal developer.created_at_before_type_cast.to_s, "2010-03-21 21:23:32"
assert_equal developer.created_at, Time.parse("2010-03-21 21:23:32")
end
def test_hash_content