From 6b33d3f81be36b772c0f0436c14a7a742062e2de Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Tue, 16 Apr 2024 05:29:34 -0400 Subject: [PATCH] Add `CustomFilter.unexpired` scope (#29896) --- app/models/custom_filter.rb | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/app/models/custom_filter.rb b/app/models/custom_filter.rb index 7c148e877..2d8f5b6cb 100644 --- a/app/models/custom_filter.rb +++ b/app/models/custom_filter.rb @@ -42,6 +42,7 @@ class CustomFilter < ApplicationRecord validate :context_must_be_valid normalizes :context, with: ->(context) { context.map(&:strip).filter_map(&:presence) } + scope :unexpired, -> { where(expires_at: nil).or where.not(expires_at: ..Time.zone.now) } before_save :prepare_cache_invalidation! before_destroy :prepare_cache_invalidation! @@ -66,14 +67,16 @@ class CustomFilter < ApplicationRecord active_filters = Rails.cache.fetch("filters:v3:#{account_id}") do filters_hash = {} - scope = CustomFilterKeyword.includes(:custom_filter).where(custom_filter: { account_id: account_id }).where(Arel.sql('expires_at IS NULL OR expires_at > NOW()')) + scope = CustomFilterKeyword.left_outer_joins(:custom_filter).merge(unexpired.where(account_id: account_id)) + scope.to_a.group_by(&:custom_filter).each do |filter, keywords| keywords.map!(&:to_regex) filters_hash[filter.id] = { keywords: Regexp.union(keywords), filter: filter } end.to_h - scope = CustomFilterStatus.includes(:custom_filter).where(custom_filter: { account_id: account_id }).where(Arel.sql('expires_at IS NULL OR expires_at > NOW()')) + scope = CustomFilterStatus.left_outer_joins(:custom_filter).merge(unexpired.where(account_id: account_id)) + scope.to_a.group_by(&:custom_filter).each do |filter, statuses| filters_hash[filter.id] ||= { filter: filter } filters_hash[filter.id].merge!(status_ids: statuses.map(&:status_id))