Created
July 3, 2014 11:43
-
-
Save troelskn/724353e3228f4f9921df to your computer and use it in GitHub Desktop.
IdentityCacheMiddleware for ThinkingSphinx
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
require 'thinking_sphinx/middlewares' | |
module ThinkingSphinx | |
module Middlewares | |
class IdentityCacheMiddleware < ActiveRecordTranslator | |
def call(contexts) | |
contexts.each do |context| | |
Inner.new(context).call | |
end | |
app.call contexts | |
end | |
class Inner < ActiveRecordTranslator::Inner | |
def results_for_models | |
@results_for_models ||= model_names.inject({}) do |hash, name| | |
model = name.constantize | |
if model < ::IdentityCache | |
Rails.logger.debug "Using IdentityCache" | |
hash[name] = model.fetch_multi(ids_for_model(name)) | |
else | |
Rails.logger.debug "Using ActiveRecord" | |
hash[name] = model_relation_with_sql_options(model.unscoped).where( | |
model.primary_key => ids_for_model(name) | |
) | |
end | |
hash | |
end | |
end | |
end | |
end | |
end | |
end | |
ThinkingSphinx::Middlewares::DEFAULT.replace(ThinkingSphinx::Middlewares::ActiveRecordTranslator, ThinkingSphinx::Middlewares::IdentityCacheMiddleware) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment