While I was DRYing up some code, I noticed that a lot of my Sunspot searches were using the same options over and over. Default scope is a nice option in ActiveRecord queries, why not in our searches?
class Item # simple default scope to add an order_by to all queries def self.default_search_scope(&additional) search = Sunspot.new_search(Item) search.build(&additional) search.build do order_by :created_at, :desc end search.execute search.results end # pardon the contrived example def self.with_keywords(user, query) default_search_scope do keywords query end end end
This way you can specify your search options in the Sunspot DSL from each method, while moving repetitive options to a single location. Clean, readable, and effective.
Great props to Mr Mat for his help