diff options
Diffstat (limited to 'activerecord/lib/active_record/type/serialized.rb')
-rw-r--r-- | activerecord/lib/active_record/type/serialized.rb | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/activerecord/lib/active_record/type/serialized.rb b/activerecord/lib/active_record/type/serialized.rb new file mode 100644 index 0000000000..42bbed7103 --- /dev/null +++ b/activerecord/lib/active_record/type/serialized.rb @@ -0,0 +1,51 @@ +module ActiveRecord + module Type + class Serialized < SimpleDelegator # :nodoc: + include Mutable + + attr_reader :subtype, :coder + + def initialize(subtype, coder) + @subtype = subtype + @coder = coder + super(subtype) + end + + def type_cast_from_database(value) + if is_default_value?(value) + value + else + coder.load(super) + end + end + + def type_cast_for_database(value) + return if value.nil? + unless is_default_value?(value) + super coder.dump(value) + end + end + + def accessor + ActiveRecord::Store::IndifferentHashAccessor + end + + def init_with(coder) + @subtype = coder['subtype'] + @coder = coder['coder'] + __setobj__(@subtype) + end + + def encode_with(coder) + coder['subtype'] = @subtype + coder['coder'] = @coder + end + + private + + def is_default_value?(value) + value == coder.load(nil) + end + end + end +end |