Skip to content

Instantly share code, notes, and snippets.

@mohitjain
Created April 15, 2014 11:31
Show Gist options
  • Select an option

  • Save mohitjain/10724785 to your computer and use it in GitHub Desktop.

Select an option

Save mohitjain/10724785 to your computer and use it in GitHub Desktop.
# Usage:
# class MyClass
# extend Sidekiq::Delayable
# def a_method(arg1, arg2)
# #...
# end
# delayed :a_method
# end
module Sidekiq
module Delayable
# delayed :a_method
# delayed :a_method, :another_method
# delayed :a_method, queue: 'a_queue'
# delayed :a_method, for: 5.minutes
# delayed :a_method, until: 5.minutes.from_now
def delayed(*args)
options = args.extract_options!
args.each do |method|
delayed_method method, options
end
end
private
def delayed_method(original_method, options = {})
now_method = "#{original_method}_now"
later_method = "#{original_method}_later"
options[:queue] ||= @queue || "default"
options[:until] = options[:until].call if options[:until].present? and options[:until].respond_to?(:call)
options[:for] = options[:for].call if options[:for].present? and options[:for].respond_to?(:call)
delay_method, delay_method_options = :delay, [options]
delay_method, delay_method_options = :delay_for, [options.delete(:for), options] if options[:for].present?
delay_method, delay_method_options = :delay_until, [options.delete(:until), options] if options[:until].present?
singleton_class.send(:define_method, later_method) do |*args|
self.send(delay_method, *delay_method_options).send(now_method, *args)
end
singleton_class.send :alias_method, now_method, original_method
singleton_class.send :alias_method, original_method, later_method
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment