1
0
Fork 0
mirror of https://github.com/paper-trail-gem/paper_trail.git synced 2022-11-09 11:33:19 -05:00
paper-trail-gem--paper_trail/lib/paper_trail/serializers/json.rb
Jared Beck 4ef8a0bfed Queries: object_changes: Simplify error instantiation
- Introduces a uniform error class, UnsupportedColumnType
- Simplifies the built-in serializers (paper_trail/serializers)

Since 9.2.0, when `object_changes_adapter` was introduced, if someone must use a
text column, and still wants to use these queries, they must write an
`object_changes_adapter`. AFAIK, no one has ever done this. The only public
adapter I know of, paper_trail-hashdiff, only supports json/b columns.

It's also theoretically possible that, after `where_object_changes` dropped
support for text columns, someone wrote a custom serializer (see
`PaperTrail.serializer=`). AFAIK, no one has done that either. Such a technique
was never documented under [6.b. Custom
Serializer](https://github.com/paper-trail-gem/paper_trail#6b-custom-serializer)
2021-04-06 12:13:04 -04:00

36 lines
1.1 KiB
Ruby

# frozen_string_literal: true
module PaperTrail
module Serializers
# An alternate serializer for, e.g. `versions.object`.
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 LIKE 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
end
end
end