File: object_attribute.rb

package info (click to toggle)
ruby-paper-trail 12.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 1,200 kB
  • sloc: ruby: 6,743; makefile: 6
file content (41 lines) | stat: -rw-r--r-- 1,129 bytes parent folder | download | duplicates (2)
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

require "paper_trail/attribute_serializers/cast_attribute_serializer"

module PaperTrail
  module AttributeSerializers
    # Serialize or deserialize the `version.object` column.
    class ObjectAttribute
      def initialize(model_class)
        @model_class = model_class
      end

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

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

      private

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

        serializer = CastAttributeSerializer.new(@model_class)
        attributes.each do |key, value|
          attributes[key] = serializer.send(serialization_method, key, value)
        end
      end

      def object_col_is_json?
        @model_class.paper_trail.version_class.object_col_is_json?
      end
    end
  end
end