Skip to content

Instantly share code, notes, and snippets.

@ayerdines
Last active January 8, 2025 13:49
Show Gist options
  • Select an option

  • Save ayerdines/fbed3ae8c04ba2e48261baecc63b09b0 to your computer and use it in GitHub Desktop.

Select an option

Save ayerdines/fbed3ae8c04ba2e48261baecc63b09b0 to your computer and use it in GitHub Desktop.
handle_asynchronously, delay with sidekiq, make sidekiq work with instance methods
class GenericJob
include Sidekiq::Job
def perform(klass, id, undelayed_method, *args)
object = klass.constantize.find(id)
object.send(undelayed_method, *args)
end
end
class Report
include Sidekiq_Dj
def generate(*args)
# code hidden
end
handle_asynchronously :generate, queue: :critical
end
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
@antarr
Copy link
Copy Markdown

antarr commented Jan 8, 2025

This is awesome

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