There is a scenario when the SerializationTypeMismatch is raised when accessing the serialized property for the 2nd time. On the first access the exception is not raised.
How to reproduce:
- Create a table and a corresponding AR class with the serialized attribute specifying the optional class. For example serialize(:preferences, Hash).
- Then, enter script/console and instantiate the instance :
>> u = UserPreferences.new
=> #<UserPreferences:0x355c294 @attributes={"updated_at"=>nil, "preferences"=>nil, "user_id"=>nil, "created_at"=>nil}, new_recordtrue
>> u.preferences
=> nil
>> u.preferences
ActiveRecord::SerializationTypeMismatch: preferences was supposed to be a Hash, but was a NilClass
from /opt/local/lib/ruby/gems/1.8/gems/activerecord-1.15.1/lib/active_record/base.rb:1951:in `unserialize_attribute'
from (eval):1:in `preferences'
from (irb):3
So the exception is raised when the u.preferences is referenced for the 2nd time. Any invocation after that repeats it.
Also, it is not clear what is the intended semantics. That is, whether it is expected to throw the first time also, or not throw if it is nil. The later looks more consistent with the existing AR behavior but by looking at the code in question, it throws anytime there is a class mismatch including NilClass.