yaml_encoder.rb 1.1 KB
Newer Older
1 2 3 4
module ActiveRecord
  class AttributeSet
    # Attempts to do more intelligent YAML dumping of an
    # ActiveRecord::AttributeSet to reduce the size of the resulting string
5
    class YAMLEncoder # :nodoc:
6 7 8 9 10
      def initialize(default_types)
        @default_types = default_types
      end

      def encode(attribute_set, coder)
11
        coder["concise_attributes"] = attribute_set.each_value.map do |attr|
12 13 14 15 16 17 18 19 20
          if attr.type.equal?(default_types[attr.name])
            attr.with_type(nil)
          else
            attr
          end
        end
      end

      def decode(coder)
21 22
        if coder["attributes"]
          coder["attributes"]
23
        else
24
          attributes_hash = Hash[coder["concise_attributes"].map do |attr|
25 26 27 28 29 30 31 32 33
            if attr.type.nil?
              attr = attr.with_type(default_types[attr.name])
            end
            [attr.name, attr]
          end]
          AttributeSet.new(attributes_hash)
        end
      end

A
Akira Matsuda 已提交
34 35
      # TODO Change this to private once we've dropped Ruby 2.2 support.
      # Workaround for Ruby 2.2 "private attribute?" warning.
36 37
      protected

38
        attr_reader :default_types
39 40 41
    end
  end
end