Skip to content

Instantly share code, notes, and snippets.

@cyx
Created November 30, 2009 09:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save cyx/245376 to your computer and use it in GitHub Desktop.
Save cyx/245376 to your computer and use it in GitHub Desktop.
module Suggestions
def self.included( base )
base.extend ClassMethods
end
module ClassMethods
# USAGE:
#
# class Doctor
# # this model should have the typical Sunspot.setup clause somewhere else
#
# include Suggestions
# end
#
# Doctor.suggestions "John Smith D"
#-
def suggestions( keywords )
prefix, full_words = prefix_and_full_words_from( keywords )
Sunspot.search(Post) do |query|
query.keywords(full_words, :fields => all_text_fields)
text_fields do |text_fields_query|
text_fields_query.any_of do |any_of_query|
all_text_fields.each do |text_field|
any_of_query.with(text_field).starting_with(prefix)
end
end
end
end
end
private
def all_text_fields
Sunspot::Setup.for(self).all_text_fields.collect(&:name)
end
def prefix_and_full_words_from( keywords )
words = keywords.split(/\s+/)
return words.pop, words.join(' ')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment