Skip to content

Instantly share code, notes, and snippets.

@jtanium
Forked from anonymous/background_session_proxy.rb
Last active December 22, 2015 16:29
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 jtanium/6499798 to your computer and use it in GitHub Desktop.
Save jtanium/6499798 to your computer and use it in GitHub Desktop.
# Written by MattBrown found at https://gist.github.com/659188
class BackgroundSessionProxy < Sunspot::SessionProxy::AbstractSessionProxy
class <<self
def async?
!!Thread.current[:background_session_proxy_async]
end
def with_async
self.async = true
begin
yield
ensure
self.async = false
end
end
def async=(async)
Thread.current[:background_session_proxy_async] = async
end
end
attr_reader :session
delegate :config, :new_search, :search, :new_more_like_this, :more_like_this,
:dirty?, :delete_dirty?, :commit, :remove, :remove!, :remove_by_id,
:remove_by_id!, :remove_all, :remove_all!, :commit_if_dirty,
:commit_if_delete_dirty, :to => :session
def initialize(session)
@session = session
end
def index(*objects)
queue_or_index_objects(objects)
end
def index!(*objects)
queue_or_index_objects(objects, commit: true)
end
private
def queue_or_index_objects(objects, options={})
if async?
Resque.enqueue(SolrWorker, id_map(objects), options.merge(time_zone: Time.zone.name))
else
session.index!(*objects)
end
end
def async?
self.class.async?
end
def id_map(objects)
map = {}
objects.each do |object|
# can't use a default proc because we're marshalling it
(map[object.class.base_class.name] ||= []) << object.id
end
map
end
end
class SolrWorker
@queue = 'solr'
def self.perform(ids, options={})
options.symbolize_keys!
options.assert_valid_keys(:time_zone, :commit)
Time.zone = options[:time_zone] if options[:time_zone]
objects = []
ids.each_pair do |class_name, instance_ids|
objects.concat(class_name.constantize.find_all_by_id(instance_ids))
end
Sunspot.index(objects)
Sunspot.commit if options[:commit]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment