Created
June 22, 2017 14:22
-
-
Save travisofthenorth/3af464ed34df003200dce2dc49091e51 to your computer and use it in GitHub Desktop.
A Chewy mixin to make searching a bit nicer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module IndexSearchable | |
extend ActiveSupport::Concern | |
class_methods do | |
def search(options = {}) | |
queries = searchable_terms.map { |term| term_search(term, options[term.to_sym]) } | |
queries << query_search(options[:query]) | |
queries.compact.reduce(:merge) | |
end | |
def query_search(query) | |
return unless query.present? | |
query(query_string: { query: "*#{query.downcase}*" }) | |
end | |
def term_search(name, value) | |
raise ArgumentError.new('Name must be specified in term search') if name.blank? | |
return unless value.present? | |
query(terms: { name.to_s => prepare_terms(value) }) | |
end | |
private | |
def searchable_terms | |
[] | |
end | |
def prepare_terms(input) | |
input = Array.wrap(input) | |
# Split any phrases/sentences up into individual words | |
terms = input.map do |value| | |
value.is_a?(String) ? value.split(' ') : value | |
end.flatten | |
# Lowercase all strings in input, since we use the standard analyzer which | |
# uses a lowercase filter by default. | |
terms.map { |value| value.is_a?(String) ? value.downcase : value } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment