Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created July 3, 2014 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/724353e3228f4f9921df to your computer and use it in GitHub Desktop.
Save troelskn/724353e3228f4f9921df to your computer and use it in GitHub Desktop.
IdentityCacheMiddleware for ThinkingSphinx
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