-
-
Save chrismealy/3129374 to your computer and use it in GitHub Desktop.
Use async methods for Sidekiq & Resque
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
# -*- encoding : utf-8 -*- | |
module AsyncResque | |
extend ActiveSupport::Concern | |
included do | |
include Sidekiq::Worker | |
def perform(*args) | |
self.class.find(args.first).send(args.last) | |
end | |
end | |
module ClassMethods | |
def queue=(name) | |
@queue = name | |
end | |
def queue | |
@queue | |
end | |
def perform(id, method, *args) | |
find(id).send(method, *args) | |
end | |
end | |
# We can pass this any Class instance method that we want to run later. | |
def async(method, *args) | |
# Rails.logger.info "ENQUEUEENE FROM CLASS!!" | |
# set the method args, set queue, remove queue arg from method args | |
new_args = set_queue(*(args)) | |
Resque.enqueue(self.class, id, method, *(new_args)) | |
end | |
private | |
def set_queue(*args) | |
new_args = [] | |
queue_setted = false | |
args.each do |arg| | |
if arg.class == Hash && arg.keys.include?(:queue) | |
self.class.queue = "#{arg[:queue]}" | |
queue_setted = true | |
else | |
new_args << arg | |
end | |
end | |
self.class.queue = self.send(:class).name.underscore.pluralize.gsub("/", "_") unless queue_setted | |
return new_args | |
end | |
end | |
ActiveRecord::Base.send :include, AsyncResque | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment