-
Notifications
You must be signed in to change notification settings - Fork 899
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
128ee1a
commit 3414859
Showing
4 changed files
with
86 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 49 additions & 0 deletions
49
lib/paper_trail/type_serializers/postgres_range_serializer.rb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
# frozen_string_literal: true | ||
|
||
module PaperTrail | ||
module TypeSerializers | ||
# Provides an alternative method of serialization | ||
# and deserialization of PostgreSQL range columns. | ||
class PostgresRangeSerializer | ||
# @see https://github.com/rails/rails/blob/main/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L147-L152 | ||
RANGE_TYPES = [ | ||
:daterange, | ||
:numrange, | ||
:tsrange, | ||
:tstzrange, | ||
:int4range, | ||
:int8range | ||
] | ||
|
||
def self.range_type?(type) | ||
RANGE_TYPES.include?(type) | ||
end | ||
|
||
def initialize(active_record_serializer) | ||
@active_record_serializer = active_record_serializer | ||
end | ||
|
||
def serialize(range) | ||
range | ||
end | ||
|
||
def deserialize(range) | ||
range.is_a?(String) ? deserialize_with_ar(range) : range | ||
end | ||
|
||
private | ||
|
||
def deserialize_with_ar(string) | ||
return nil if string.blank? | ||
|
||
delimiter = string[/\.{2,3}/] | ||
range_start, range_end = string.split(delimiter) | ||
|
||
range_start = @active_record_serializer.subtype.cast(range_start) | ||
range_end = @active_record_serializer.subtype.cast(range_end) | ||
|
||
Range.new(range_start, range_end, exclude_end: delimiter == '...') | ||
end | ||
end | ||
end | ||
end |