Created
November 2, 2010 02:37
-
-
Save anonymous/659188 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 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) | |
if async? | |
Resque.enqueue(SolrWorker, id_map(objects), :time_zone => Time.zone.to_s) | |
else | |
session.index(*objects) | |
end | |
end | |
def index!(*objects) | |
if async? | |
Resque.enqueue(SolrWorker, id_map(objects), :commit => true, | |
:time_zone => Time.zone.name) | |
else | |
session.index!(*objects) | |
end | |
end | |
private | |
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
FYI, there's a small bug on line #34:
... should be: