Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add enhanced filter to autocomplete #221

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions lib/scoped_search/auto_complete_builder.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
12 changes: 12 additions & 0 deletions spec/integration/auto_complete_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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