Skip to content

Instantly share code, notes, and snippets.

@rheaton
Last active December 22, 2015 09:39
Show Gist options
  • Save rheaton/6453454 to your computer and use it in GitHub Desktop.
Save rheaton/6453454 to your computer and use it in GitHub Desktop.
Base Resque Job For instance methods & correct term exception handling (b/c of rails's re-raising of errors with a different class).
# example job (for emails)
class EmailJob < Jobs::Base
@queue = :mailer
attr_reader :mailer, :params, :email_type
def initialize(mailer_class, email_type, params={})
@mailer = mailer_class.constantize
@params = params.with_indifferent_access
@email_type = email_type
end
def run
email = if params[:object]
object = params[:object][:class].find(params[:object][:id])
mailer.send(email_type, object)
elsif params[:args]
mailer.send(email_type, *params[:args])
end
email.deliver
end
end
class Jobs::Base
TERM_MATCHER = /#{Regexp.escape("Resque::TermException")}/
def self.perform(*args)
job = self.new(*args)
job.run
rescue Resque::TermException
Resque.enqueue(self, *args)
rescue => e
# we have to match because Rails is stupid sometimes and doesn't re-raise the same error!
if e.message =~ TERM_MATCHER
Resque.enqueue(self, *args)
else
raise e
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment