Skip to content

Instantly share code, notes, and snippets.

@katpadi
Last active February 12, 2017 08:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save katpadi/c957c3229a554e1bb2e9f73605e84041 to your computer and use it in GitHub Desktop.
Save katpadi/c957c3229a554e1bb2e9f73605e84041 to your computer and use it in GitHub Desktop.
Autocomplete Kups Search
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