Allow instance methods to be delayed to Sidekiq
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
# Idea from http://krautcomputing.com/blog/2012/10/07/how-to-make-everything-background-processable-through-sidekiq/ | |
# | |
# Usage: | |
# | |
# class Synchronization | |
# include Asyncable | |
# end | |
# | |
# Then: | |
# Synchronization.find(12).perform_async(:synchronize, 3, 2) | |
# will result in: | |
# Synchronization.find_by_async_id(12).synchronize(3, 2) | |
# | |
# NOTE: You can of course replace #async_id and .find_by_async_id methods =) | |
module Asyncable | |
extend ActiveSupport::Concern | |
%i[perform_async perform_in].each do |method_name| | |
define_method method_name do |*args| | |
Caller.send method_name, *args, {async_id: async_id, class_name: self.class.name} | |
end | |
end | |
alias_method :perform_at, :perform_in | |
protected | |
# Unique ID of this object, which will be used in #find_by_async_id() to get this object in async worker. | |
def async_id | |
id | |
end | |
module ClassMethods | |
# When executing the method in an async method, we'll find this object using this method. | |
def find_by_async_id(async_id) | |
find(async_id) | |
end | |
end | |
class Caller | |
include Sidekiq::Worker | |
def perform(*args) | |
options = args.pop | |
options['class_name'].constantize.find_by_async_id( options['async_id'] ).send(*args) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Some another example: