From 2dc3279b092de47aa9667d629732732d31eb5cce Mon Sep 17 00:00:00 2001 From: Thorben Denzer Date: Tue, 4 Jun 2024 16:11:08 +0200 Subject: [PATCH 1/2] Add "enhanced_filter" to AutoCompleteBuilder - "enhanced_filter" requires a given column to be present before doing any filtering - "enhanced_filter" takes precedence over "value_filter" --- lib/scoped_search/auto_complete_builder.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/lib/scoped_search/auto_complete_builder.rb b/lib/scoped_search/auto_complete_builder.rb index 0ad5bf68..9ebd74cc 100644 --- a/lib/scoped_search/auto_complete_builder.rb +++ b/lib/scoped_search/auto_complete_builder.rb @@ -207,8 +207,7 @@ def complete_value def complete_value_from_db(field, special_values, val) count = 20 - special_values.count - completer_scope(field) - .where(@options[:value_filter]) + filtered_completer_scope(field) .where(value_conditions(field.quoted_field, val)) .select(field.quoted_field) .limit(count) @@ -218,6 +217,15 @@ def complete_value_from_db(field, special_values, val) .map { |v| v.to_s =~ /\s/ ? "\"#{v.gsub('"', '\"')}\"" : v } end + def filtered_completer_scope(field) + scope = completer_scope(field) + return scope.where(@options[:value_filter]) unless @options[:enhanced_filter] + if field.klass.column_names.include?(@options[:enhanced_filter][:has_column]) + return scope.where(@options[:enhanced_filter][:filter]) + end + scope + end + def completer_scope(field) klass = field.klass scope = klass.respond_to?(:completer_scope) ? klass.completer_scope(@options) : klass From f534c9fe58c31f0eee33a7947283e1117b841c0f Mon Sep 17 00:00:00 2001 From: Thorben Denzer Date: Wed, 5 Jun 2024 09:52:14 +0200 Subject: [PATCH 2/2] Add test for enhanced_filter --- spec/integration/auto_complete_spec.rb | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/spec/integration/auto_complete_spec.rb b/spec/integration/auto_complete_spec.rb index 478721d2..da493ce4 100644 --- a/spec/integration/auto_complete_spec.rb +++ b/spec/integration/auto_complete_spec.rb @@ -267,5 +267,17 @@ class ::Infoo < ::Foo Foo.complete_for('int =', value_filter: { qux_id: 99 }).should == [] end end + + context 'autocompleting with enhanced_filter' do + it 'should return filtered values' do + Foo.complete_for('int =', enhanced_filter: { has_column: "int", filter: { qux_id: @qux_2.id } }).should == ['int = 10'] + end + it 'should take precedence over value_filter' do + Foo.complete_for('int =', value_filter: { qux_id: @qux_1.id }, enhanced_filter: { has_column: "int", filter: { qux_id: @qux_2.id } }).should == ['int = 10'] + end + it 'should ignore invalid filter' do + Foo.complete_for('int =', enhanced_filter: { has_column: "invalid_column_name", filter: { qux_id: @qux_1.id } }).should == ["int = 9", "int = 10", "int = 22"] + end + end end end