Skip to content

Instantly share code, notes, and snippets.

Created November 2, 2010 02:37
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/659188 to your computer and use it in GitHub Desktop.
Save anonymous/659188 to your computer and use it in GitHub Desktop.
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
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
@jtanium
Copy link

jtanium commented Sep 9, 2013

FYI, there's a small bug on line #34:

:time_zone => Time.zone.to_s

... should be:

:time_zone => Time.zone.name

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment