From e7f8e334327504d7041e14cefccdcb3a29d25408 Mon Sep 17 00:00:00 2001 From: Duncan Beevers Date: Fri, 8 Aug 2008 15:52:52 -0700 Subject: [PATCH] Setting date attributes casts to Date. --- .../lib/active_record/attribute_methods.rb | 9 ++++++--- .../abstract/schema_definitions.rb | 4 ++++ activerecord/test/cases/attribute_methods_test.rb | 6 ++++++ 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/activerecord/lib/active_record/attribute_methods.rb b/activerecord/lib/active_record/attribute_methods.rb index 2db2722..02d7d0a 100644 --- a/activerecord/lib/active_record/attribute_methods.rb +++ b/activerecord/lib/active_record/attribute_methods.rb @@ -288,15 +288,18 @@ module ActiveRecord # Updates the attribute identified by attr_name with the specified +value+. Empty strings for fixnum and float - # columns are turned into nil. + # columns are turned into nil. Time and DateTime values for Date columns are turned into dates def write_attribute(attr_name, value) attr_name = attr_name.to_s @attributes_cache.delete(attr_name) if (column = column_for_attribute(attr_name)) && column.number? - @attributes[attr_name] = convert_number_column_value(value) + converted_value = convert_number_column_value(value) + elsif !value.blank? && column && column.date? + converted_value = value.to_date else - @attributes[attr_name] = value + converted_value = value end + @attributes[attr_name] = converted_value end diff --git a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb index d73ffc3..acae933 100644 --- a/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb +++ b/activerecord/lib/active_record/connection_adapters/abstract/schema_definitions.rb @@ -37,6 +37,10 @@ module ActiveRecord [:float, :integer, :decimal].include? type end + def date? + :date == type + end + # Returns the Ruby class that corresponds to the abstract data type. def klass case type diff --git a/activerecord/test/cases/attribute_methods_test.rb b/activerecord/test/cases/attribute_methods_test.rb index c336fd9..fab6f33 100755 --- a/activerecord/test/cases/attribute_methods_test.rb +++ b/activerecord/test/cases/attribute_methods_test.rb @@ -114,6 +114,12 @@ class AttributeMethodsTest < ActiveRecord::TestCase assert_equal time_related_columns_on_topic.sort, Topic.cached_attributes.sort end + def test_date_columns_cast_values_to_date + date = Topic.new(:last_read => Time.now).last_read + assert_kind_of Date, date + assert_equal Date.today, date + end + def test_accessing_cached_attributes_caches_the_converted_values_and_nothing_else t = topics(:first) cache = t.instance_variable_get "@attributes_cache" -- 1.5.5