From 01b624c4a0d17ec24f6acf56298fe9e5e8a6dd49 Mon Sep 17 00:00:00 2001
From: Matt Jankowski <matt@jankowski.online>
Date: Wed, 13 Mar 2024 04:50:21 -0400
Subject: [PATCH] Use `normalizes` on `CustomFilter#context` value (#27602)

---
 app/models/custom_filter.rb       | 6 +-----
 spec/models/custom_filter_spec.rb | 8 ++++++++
 2 files changed, 9 insertions(+), 5 deletions(-)

diff --git a/app/models/custom_filter.rb b/app/models/custom_filter.rb
index 5e2d152e3..7c148e877 100644
--- a/app/models/custom_filter.rb
+++ b/app/models/custom_filter.rb
@@ -41,7 +41,7 @@ class CustomFilter < ApplicationRecord
   validates :title, :context, presence: true
   validate :context_must_be_valid
 
-  before_validation :clean_up_contexts
+  normalizes :context, with: ->(context) { context.map(&:strip).filter_map(&:presence) }
 
   before_save :prepare_cache_invalidation!
   before_destroy :prepare_cache_invalidation!
@@ -114,10 +114,6 @@ class CustomFilter < ApplicationRecord
 
   private
 
-  def clean_up_contexts
-    self.context = Array(context).map(&:strip).filter_map(&:presence)
-  end
-
   def context_must_be_valid
     errors.add(:context, I18n.t('filters.errors.invalid_context')) if invalid_context_value?
   end
diff --git a/spec/models/custom_filter_spec.rb b/spec/models/custom_filter_spec.rb
index 940493633..8ac9dbb89 100644
--- a/spec/models/custom_filter_spec.rb
+++ b/spec/models/custom_filter_spec.rb
@@ -32,4 +32,12 @@ RSpec.describe CustomFilter do
       expect(record).to model_have_error_on_field(:context)
     end
   end
+
+  describe 'Normalizations' do
+    it 'cleans up context values' do
+      record = described_class.new(context: ['home', 'notifications', 'public    ', ''])
+
+      expect(record.context).to eq(%w(home notifications public))
+    end
+  end
 end