Skip to content

Commit

Permalink
Clamp dates when serializing to Elasticsearch API (#28081)
Browse files Browse the repository at this point in the history
  • Loading branch information
ClearlyClaire committed Nov 28, 2023
1 parent eeeb4d6 commit acca352
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 2 deletions.
4 changes: 3 additions & 1 deletion app/chewy/accounts_index.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true

class AccountsIndex < Chewy::Index
include DatetimeClampingConcern

settings index: { refresh_interval: '30s' }, analysis: {
analyzer: {
content: {
Expand Down Expand Up @@ -38,6 +40,6 @@ class AccountsIndex < Chewy::Index

field :following_count, type: 'long', value: ->(account) { account.following_count }
field :followers_count, type: 'long', value: ->(account) { account.followers_count }
field :last_status_at, type: 'date', value: ->(account) { account.last_status_at || account.created_at }
field :last_status_at, type: 'date', value: ->(account) { clamp_date(account.last_status_at || account.created_at) }
end
end
14 changes: 14 additions & 0 deletions app/chewy/concerns/datetime_clamping_concern.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# frozen_string_literal: true

module DatetimeClampingConcern
extend ActiveSupport::Concern

MIN_ISO8601_DATETIME = '0000-01-01T00:00:00Z'.to_datetime.freeze
MAX_ISO8601_DATETIME = '9999-12-31T23:59:59Z'.to_datetime.freeze

class_methods do
def clamp_date(datetime)
datetime.clamp(MIN_ISO8601_DATETIME, MAX_ISO8601_DATETIME)
end
end
end
4 changes: 3 additions & 1 deletion app/chewy/tags_index.rb
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# frozen_string_literal: true

class TagsIndex < Chewy::Index
include DatetimeClampingConcern

settings index: { refresh_interval: '30s' }, analysis: {
analyzer: {
content: {
Expand Down Expand Up @@ -36,6 +38,6 @@ class TagsIndex < Chewy::Index

field :reviewed, type: 'boolean', value: ->(tag) { tag.reviewed? }
field :usage, type: 'long', value: ->(tag, crutches) { tag.history.aggregate(crutches.time_period).accounts }
field :last_status_at, type: 'date', value: ->(tag) { tag.last_status_at || tag.created_at }
field :last_status_at, type: 'date', value: ->(tag) { clamp_date(tag.last_status_at || tag.created_at) }
end
end

0 comments on commit acca352

Please sign in to comment.