Forked from anonymous/background_session_proxy.rb
Last active
December 22, 2015 16:29
-
-
Save jtanium/6499798 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
# 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 |
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 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