aboutsummaryrefslogtreecommitdiffstats
path: root/activemodel/lib/active_model/attribute_set/yaml_encoder.rb
blob: 4ea945b9565c5d2730f902d1e2ed38f4e3943ede (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
# frozen_string_literal: true

module ActiveModel
  class AttributeSet
    # Attempts to do more intelligent YAML dumping of an
    # ActiveModel::AttributeSet to reduce the size of the resulting string
    class YAMLEncoder # :nodoc:
      def initialize(default_types)
        @default_types = default_types
      end

      def encode(attribute_set, coder)
        coder["concise_attributes"] = attribute_set.each_value.map do |attr|
          if attr.type.equal?(default_types[attr.name])
            attr.with_type(nil)
          else
            attr
          end
        end
      end

      def decode(coder)
        if coder["attributes"]
          coder["attributes"]
        else
          attributes_hash = Hash[coder["concise_attributes"].map do |attr|
            if attr.type.nil?
              attr = attr.with_type(default_types[attr.name])
            end
            [attr.name, attr]
          end]
          AttributeSet.new(attributes_hash)
        end
      end

      protected

        attr_reader :default_types
    end
  end
end