serialized.rb 1.1 KB
Newer Older
1 2 3
module ActiveRecord
  module Type
    class Serialized < SimpleDelegator # :nodoc:
4
      include Mutable
5
      include Decorator
6

7
      attr_reader :subtype, :coder
8

9
      def initialize(subtype, coder)
10
        @subtype = subtype
11 12
        @coder = coder
        super(subtype)
13 14
      end

15
      def type_cast_from_database(value)
16
        if default_value?(value)
17
          value
18
        else
19
          coder.load(super)
20 21 22
        end
      end

23
      def type_cast_for_database(value)
24
        return if value.nil?
25
        unless default_value?(value)
26
          super coder.dump(value)
27
        end
28 29
      end

30 31 32 33 34
      def changed_in_place?(raw_old_value, value)
        return false if value.nil?
        subtype.changed_in_place?(raw_old_value, coder.dump(value))
      end

35 36 37
      def accessor
        ActiveRecord::Store::IndifferentHashAccessor
      end
38

39 40
      def init_with(coder)
        @coder = coder['coder']
41
        super
42 43 44 45
      end

      def encode_with(coder)
        coder['coder'] = @coder
46
        super
47 48
      end

49
      private
50

51
      def default_value?(value)
52
        value == coder.load(nil)
53
      end
54 55 56
    end
  end
end