Created
December 11, 2014 14:55
-
-
Save ColinTheRobot/3e54b6a0cba84fa22812 to your computer and use it in GitHub Desktop.
fuzzy-ish search algorithm on model.
This file contains 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
# This algorithm is incomplete | |
# It is a fuzzy search for first_name, last_name, and user_name | |
def self.search(params) | |
params.downcase! | |
query = params.split | |
results = [] | |
query.each do |f| | |
search_condition = "%#{f}%" | |
raw_result = where('lower(first_name) LIKE ? OR lower(last_name) LIKE ?' \ | |
'OR lower(user_name) LIKE ?', | |
search_condition, | |
search_condition, | |
search_condition | |
) | |
results << raw_result | |
end | |
sanitize_results(results) | |
if results.count > 1 && query.count > 1 | |
check_for_exact_match(results, params) || results.uniq | |
else | |
results || [] | |
end | |
end | |
private | |
def self.sanitize_results(results) | |
results.flatten! | |
results.uniq | |
end | |
def self.check_for_exact_match(sanitized_results, params) | |
sanitized_results.each do |user| | |
full_name = "#{user.first_name} #{user.last_name}" | |
@exact_match = user if full_name.downcase === params | |
end | |
@exact_match | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment