Sha256: 1ef43ebf08fd9f3b25969b728ab6b75d5f6127977f134c9f461e8ece4d266bdc

Contents?: true

Size: 1.22 KB

Versions: 2

Compression:

Stored size: 1.22 KB

Contents

require "paper_trail/attribute_serializers/cast_attribute_serializer"

module PaperTrail
  module AttributeSerializers
    # Serialize or deserialize the `version.object_changes` column.
    class ObjectChangesAttribute
      def initialize(item_class)
        @item_class = item_class
      end

      def serialize(changes)
        alter(changes, :serialize)
      end

      def deserialize(changes)
        alter(changes, :deserialize)
      end

      private

      # Modifies `changes` in place.
      # TODO: Return a new hash instead.
      def alter(changes, serialization_method)
        # Don't serialize before values before inserting into columns of type
        # `JSON` on `PostgreSQL` databases.
        return changes if object_changes_col_is_json?

        serializer = CastAttributeSerializer.new(@item_class)
        changes.clone.each do |key, change|
          # `change` is an Array with two elements, representing before and after.
          changes[key] = Array(change).map do |value|
            serializer.send(serialization_method, key, value)
          end
        end
      end

      def object_changes_col_is_json?
        @item_class.paper_trail_version_class.object_changes_col_is_json?
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
paper_trail-5.1.1 lib/paper_trail/attribute_serializers/object_changes_attribute.rb
paper_trail-5.1.0 lib/paper_trail/attribute_serializers/object_changes_attribute.rb