diff options
Diffstat (limited to 'activerecord/lib/active_record')
-rw-r--r-- | activerecord/lib/active_record/base.rb | 24 | ||||
-rw-r--r-- | activerecord/lib/active_record/coders/yaml_column.rb | 2 |
2 files changed, 22 insertions, 4 deletions
diff --git a/activerecord/lib/active_record/base.rb b/activerecord/lib/active_record/base.rb index 0941700803..e0957e2849 100644 --- a/activerecord/lib/active_record/base.rb +++ b/activerecord/lib/active_record/base.rb @@ -249,6 +249,17 @@ module ActiveRecord #:nodoc: # user = User.create(:preferences => %w( one two three )) # User.find(user.id).preferences # raises SerializationTypeMismatch # + # When you specify a class option, the default value for that attribute will be a new + # instance of that class. + # + # class User < ActiveRecord::Base + # serialize :preferences, OpenStruct + # end + # + # user = User.new + # user.preferences.theme_color = "red" + # + # # == Single table inheritance # # Active Record allows inheritance by storing the name of the class in a column that by @@ -1409,6 +1420,7 @@ MSG @changed_attributes = {} ensure_proper_type + set_serialized_attributes populate_with_current_scope_attributes self.attributes = attributes unless attributes.nil? @@ -1447,10 +1459,7 @@ MSG def init_with(coder) @attributes = coder['attributes'] - (@attributes.keys & self.class.serialized_attributes.keys).each do |key| - coder = self.class.serialized_attributes[key] - @attributes[key] = coder.load @attributes[key] - end + set_serialized_attributes @attributes_cache, @previously_changed, @changed_attributes = {}, {}, {} @association_cache = {} @@ -1461,6 +1470,13 @@ MSG run_callbacks :initialize end + def set_serialized_attributes + (@attributes.keys & self.class.serialized_attributes.keys).each do |key| + coder = self.class.serialized_attributes[key] + @attributes[key] = coder.load @attributes[key] + end + end + # Specifies how the record is dumped by +Marshal+. # # +_dump+ emits a marshalled hash which has been passed to +encode_with+. Override this diff --git a/activerecord/lib/active_record/coders/yaml_column.rb b/activerecord/lib/active_record/coders/yaml_column.rb index fcecc11aba..fb59d9fb07 100644 --- a/activerecord/lib/active_record/coders/yaml_column.rb +++ b/activerecord/lib/active_record/coders/yaml_column.rb @@ -19,6 +19,7 @@ module ActiveRecord end def load(yaml) + return object_class.new if object_class != Object && yaml.nil? return yaml unless yaml.is_a?(String) && yaml =~ /^---/ begin obj = YAML.load(yaml) @@ -27,6 +28,7 @@ module ActiveRecord raise SerializationTypeMismatch, "Attribute was supposed to be a #{object_class}, but was a #{obj.class}" end + obj ||= object_class.new if object_class != Object obj rescue *RESCUE_ERRORS |