Skip to content

Instantly share code, notes, and snippets.

@ColinTheRobot
Created December 11, 2014 14:55
Show Gist options
  • Save ColinTheRobot/3e54b6a0cba84fa22812 to your computer and use it in GitHub Desktop.
Save ColinTheRobot/3e54b6a0cba84fa22812 to your computer and use it in GitHub Desktop.
fuzzy-ish search algorithm on model.
# 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