Sha256: 5725f50cefc72c92e65150d2c7e40e5a7e0c43e9cab700bab8be582d71628e6a

Contents?: true

Size: 1.58 KB

Versions: 8

Compression:

Stored size: 1.58 KB

Contents

require 'active_support/json'

module PaperTrail
  module Serializers
    module JSON
      extend self # makes all instance methods become module methods as well

      def load(string)
        ActiveSupport::JSON.decode string
      end

      def dump(object)
        ActiveSupport::JSON.encode object
      end

      # Returns a SQL condition to be used to match the given field and value
      # in the serialized object
      def where_object_condition(arel_field, field, value)
        # Convert to JSON to handle strings and nulls correctly.
        json_value = value.to_json

        # If the value is a number, we need to ensure that we find the next
        # character too, which is either `,` or `}`, to ensure that searching
        # for the value 12 doesn't yield false positives when the value is
        # 123.
        if value.is_a? Numeric
          arel_field.matches("%\"#{field}\":#{json_value},%").
            or(
          arel_field.matches("%\"#{field}\":#{json_value}}%"))
        else
          arel_field.matches("%\"#{field}\":#{json_value}%")
        end
      end

      # Returns a SQL condition to be used to match the given field and value
      # in the serialized object_changes
      def where_object_changes_condition(arel_field, field, value)
        # Convert to JSON to handle strings and nulls correctly.
        json_value = value.to_json

        # Need to check first (before) and secondary (after) fields
        arel_field.matches("%\"#{field}\":[#{json_value},%").
          or(arel_field.matches("%\"#{field}\":[%,#{json_value}]%"))
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
paper_trail-4.2.0 lib/paper_trail/serializers/json.rb
paper_trail-4.1.0 lib/paper_trail/serializers/json.rb
paper_trail-4.0.2 lib/paper_trail/serializers/json.rb
paper_trail-4.0.1 lib/paper_trail/serializers/json.rb
paper_trail-4.0.0 lib/paper_trail/serializers/json.rb
paper_trail-4.0.0.rc2 lib/paper_trail/serializers/json.rb
paper_trail-4.0.0.rc1 lib/paper_trail/serializers/json.rb
paper_trail-4.0.0.beta2 lib/paper_trail/serializers/json.rb