aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/type/serialized.rb
blob: a1205fa819f8061e3bb2bf8126839a584fe33c92 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module ActiveRecord
  module Type
    class Serialized < SimpleDelegator # :nodoc:
      attr_reader :subtype, :coder

      def initialize(subtype, coder)
        @subtype = subtype
        @coder = coder
        super(subtype)
      end

      def type_cast(value)
        if is_default_value?(value)
          value
        else
          coder.load(super)
        end
      end

      def type_cast_from_user(value)
        type_cast(type_cast_for_database(value))
      end

      def type_cast_for_database(value)
        return if value.nil?
        unless is_default_value?(value)
          super coder.dump(value)
        end
      end

      def serialized?
        true
      end

      def accessor
        ActiveRecord::Store::IndifferentHashAccessor
      end

      private

      def is_default_value?(value)
        value == coder.load(nil)
      end
    end
  end
end