diff options
Diffstat (limited to 'activerecord/lib/active_record/type/serialized.rb')
-rw-r--r-- | activerecord/lib/active_record/type/serialized.rb | 35 |
1 files changed, 32 insertions, 3 deletions
diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb index cc7513ca2a..4052ac0fa0 100644 --- a/activerecord/lib/active_record/type/serialized.rb +++ b/activerecord/lib/active_record/type/serialized.rb @@ -1,11 +1,12 @@ module ActiveRecord module Type class Serialized < SimpleDelegator # :nodoc: - attr_reader :subtype + attr_reader :subtype, :coder - def initialize(subtype) + def initialize(subtype, coder) @subtype = subtype - super + @coder = coder + super(subtype) end def type_cast(value) @@ -16,6 +17,14 @@ module ActiveRecord end end + def type_cast_for_write(value) + Attribute.new(coder, value, :unserialized) + end + + def raw_type_cast_for_write(value) + Attribute.new(coder, value, :serialized) + end + def serialized? true end @@ -23,6 +32,26 @@ module ActiveRecord def accessor ActiveRecord::Store::IndifferentHashAccessor end + + class Attribute < Struct.new(:coder, :value, :state) # :nodoc: + def unserialized_value(v = value) + state == :serialized ? unserialize(v) : value + end + + def serialized_value + state == :unserialized ? serialize : value + end + + def unserialize(v) + self.state = :unserialized + self.value = coder.load(v) + end + + def serialize + self.state = :serialized + self.value = coder.dump(value) + end + end end end end |