-
-
Save karlhigley/5817180 to your computer and use it in GitHub Desktop.
This file contains 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
class PostController < ApplicationController | |
def search | |
searcher.search(params[:keywords]) | |
end | |
private | |
def searcher | |
Feature::Set.toggled_on?(:some_feature) ? SunspotPostSearcher.new : AnotherPostSearcher.new | |
end | |
end | |
# Knows nothing about searching | |
class Post | |
# ... | |
end | |
# Knows how to instantiate Posts from search results | |
class SunspotPostSearcher < SunspotSearcherWithInstrumentation | |
def search(keywords, sort_order = default_sort_order) | |
super(keywords, sort_order).results.map do |result| | |
make_post(result) | |
end | |
end | |
private | |
# Instantiates Post from result | |
def make_post(result) | |
# ... | |
end | |
def default_sort_order | |
{:field => :published_at, :dir => :desc} | |
end | |
# Overrides super-class method | |
def search_type | |
:sunspot_post_search | |
end | |
end | |
# Like SunspotPostSearcher above, knows how to instantiate posts from | |
# whatever its backend returns | |
class AnotherPostSearcher < SomeOtherSearchBackend | |
# ... | |
end | |
class SunspotSearcherWithInstrumentation | |
def initialize(options = {}) | |
@instrumentation = options[:instrumentation] || Instrumentation.new | |
@searcher = options[:searcher] || SunspotSearcher.new | |
end | |
def search(keywords, sort_order = nil) | |
super(keywords, sort_order).tap do |documents| | |
@instrumentation.register_event(search_type, keywords) | |
@instrumentation.raise_alarm(search_type, 'empty!') if documents.empty? | |
end | |
end | |
private | |
# Can be overridden by subclasses | |
def search_type | |
:sunspot_search | |
end | |
end | |
class Instrumentation | |
def initialize(options = {}) | |
@stats_collector = options[:stats_collector] || StatsCollector.new | |
@alarm_handler = options[:alarm_handler] || AlarmHandler.new | |
end | |
def register_event(event_type, event_data) | |
@stats_collector.register_event(event_type, event_data) | |
end | |
def raise_alarm(type, description) | |
@alarm_handler.raise(type, description) | |
end | |
end | |
class SunspotSearcher | |
def search(keywords, sort_order = nil) | |
Sunspot.search do | |
fulltext keywords | |
order_by sort_order[:field], sort_order[:dir] if sort_order | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment