Skip to content

Instantly share code, notes, and snippets.

@heycarsten
Created October 30, 2009 16:40
Show Gist options
  • Save heycarsten/222509 to your computer and use it in GitHub Desktop.
Save heycarsten/222509 to your computer and use it in GitHub Desktop.
module LCBO
class SearchSuggest
STOP_WORDS = %w[ woods ]
require 'amatch'
require 'stringex'
def initialize(db)
@db = db
populate_dictionary!
end
def query(term)
dterm = term.downcase
@dictionary.inject({}) do |hsh, word|
hsh.merge(Amatch::Levenshtein.new(word).match(dterm) => word)
end.min[1]
end
private
def populate_dictionary!
@dictionary = @db.connection[:products].
select(:name).
all.
map do |row|
row[:name].
to_ascii.
downcase.
gsub(/[0-9]+|[\*\'\.]/, '').
gsub('-', ' ').
strip.
split
end.
flatten.
reject! do |word|
word.length < 5 ||
STOP_WORDS.include?(word)
end.
uniq.
sort
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment