Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #7293: add_nil_support_to_serialize.diff

File add_nil_support_to_serialize.diff, 1.8 kB (added by sandofsky, 2 years ago)

Patch includes code, tests, and update to documentation.

  • test/base_test.rb

    old new  
    11181118 
    11191119  def test_serialized_attribute_with_class_constraint 
    11201120    myobj = MyObject.new('value1', 'value2') 
    1121     topic = Topic.create("content" => myobj) 
     1121    topic = Topic.new 
     1122    assert_nil topic.content 
     1123     
     1124    topic.content = myobj 
     1125    assert topic.save 
    11221126    Topic.serialize(:content, Hash) 
    11231127 
    11241128    assert_raise(ActiveRecord::SerializationTypeMismatch) { Topic.find(topic.id).content } 
  • lib/active_record/base.rb

    old new  
    574574 
    575575      # Specifies that the attribute by the name of +attr_name+ should be serialized before saving to the database and unserialized 
    576576      # after loading from the database. The serialization is done through YAML. If +class_name+ is specified, the serialized 
    577       # object must be of that class on retrieval or +SerializationTypeMismatch+ will be raised. 
     577      # object must be of that class on retrieval, or nil. Otherwise, +SerializationTypeMismatch+ will be raised. 
    578578      def serialize(attr_name, class_name = Object) 
    579579        serialized_attributes[attr_name.to_s] = class_name 
    580580      end 
     
    19581958      def unserialize_attribute(attr_name) 
    19591959        unserialized_object = object_from_yaml(@attributes[attr_name]) 
    19601960 
    1961         if unserialized_object.is_a?(self.class.serialized_attributes[attr_name]) 
     1961        if unserialized_object.is_a?(self.class.serialized_attributes[attr_name]) || unserialized_object.nil? 
    19621962          @attributes[attr_name] = unserialized_object 
    19631963        else 
    19641964          raise SerializationTypeMismatch,