Last active
February 12, 2017 08:26
-
-
Save katpadi/c957c3229a554e1bb2e9f73605e84041 to your computer and use it in GitHub Desktop.
Autocomplete Kups Search
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
class AutocompleteSearch | |
class << self | |
def populate(query_scope) | |
query_scope.find_each do |item| | |
name = item.label | |
json_data = format_data(item) | |
name.length.times do |n| | |
key = name[0, n+1] | |
$redis.zadd "kupsearch:#{key.downcase}", 1, json_data | |
end | |
end | |
end | |
def format_data(subject) | |
{ | |
id: subject.id, | |
name: subject.name, | |
label: subject.label, | |
type: subject.class.name | |
}.to_json | |
end | |
def results_for(term, max = 5) | |
return [] if term.blank? | |
results = $redis.zrevrange "kupsearch:#{term.downcase}", 0, max-1 | |
results.map { |result| JSON.parse(result, symbolize_names: true) } | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment