Created
October 30, 2009 16:40
-
-
Save heycarsten/222509 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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