-
-
Save pbharadiya/e61f46768bbdc490ecfd3195fb57c13e to your computer and use it in GitHub Desktop.
handle_asynchronously, delay with sidekiq, make sidekiq work with instance methods
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 GenericJob | |
include Sidekiq::Job | |
def perform(klass, id, undelayed_method, *args) | |
object = klass.constantize.find(id) | |
object.send(undelayed_method, *args) | |
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 Report | |
include Sidekiq_Dj | |
def generate(*args) | |
# code hidden | |
end | |
handle_asynchronously :generate, queue: :critical | |
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
module Sidekiq_Dj | |
extend ActiveSupport::Concern | |
included do | |
def delay(options={}) | |
Delayer.new(self, options) | |
end | |
end | |
class_methods do | |
def handle_asynchronously(method, options={}) | |
delayed_method = "#{method}_delayed" | |
undelayed_method = "#{method}_undelayed" | |
define_method("#{delayed_method}") do |*args| | |
if self.is_a?(Class) | |
raise ArgumentError, "Sidekiq_Dj extension doesn't work with class methods." | |
end | |
delay(options).send(undelayed_method, *args) | |
end | |
alias_method undelayed_method, method | |
alias_method method, delayed_method | |
end | |
end | |
class Delayer | |
def initialize(target, options) | |
@target = target | |
@options = options | |
end | |
def method_missing(method, *args) | |
GenericJob.set(@options).perform_async(@target.class.to_s, @target.id, method, *stringify_hash_keys(args)) | |
end | |
def stringify_hash_keys(args) | |
args.map do |arg| | |
case arg | |
when Hash | |
arg.deep_stringify_keys | |
when Array | |
stringify_hash_keys(arg) | |
else | |
arg | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment