Skip to content

Instantly share code, notes, and snippets.

@dodecaphonic
Last active December 16, 2015 20:49
Show Gist options
  • Save dodecaphonic/5495130 to your computer and use it in GitHub Desktop.
Save dodecaphonic/5495130 to your computer and use it in GitHub Desktop.
A very-much-in-need-of-improvement way to replace DelayedJob with SuckerPunch for your application mailers.
class DelayableMailer < ActionMailer::Base
class QueueSetupError < StandardError; end
class << self
def queue(options)
@queue_name = options.fetch(:name)
@workers = options.fetch(:workers) { 2 }
setup_queue
end
def delay
if !setup?
raise QueueSetupError, "please setup a queue before using a Delayable"
end
DelayedMethod.new(@queue_name)
end
def setup?
!!@setup
end
def setup_queue
scope = self
worker = Class.new do
include SuckerPunch::Worker
define_method(:perform) do |method_name, *args|
ActiveRecord::Base.connection_pool.with_connection do
scope.public_send(method_name, *args).deliver
end
end
end
SuckerPunch.queue name: @queue_name, worker: worker, workers: @workers
@setup = true
end
end
class DelayedMethod
attr_reader :queue_name
private :queue_name
def initialize(queue_name)
@queue_name = queue_name
end
def method_missing(method_name, *args)
SuckerPunch::Queue[queue_name].async.perform(method_name.to_sym, *args)
end
end
end
class SampleMailer < DelayableMailer
queue :sample_mailer_queue
def sample_message(user_id)
# ...
end
end
user = User.find(1)
# ...
SampleMailer.delay.sample_message(user.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment