Best practice on structuring asynchronous mailers (using Sidekiq)

Posted by gbdev on Stack Overflow See other posts from Stack Overflow or by gbdev
Published on 2013-10-27T02:50:45Z Indexed on 2013/10/27 3:54 UTC
Read the original article Hit count: 165

Just wondering what's the best way to go about structuring asynchronous mailers in my Rails app (using Sidekiq)? I have one ActionMailer class with multiple methods/emails...

notifier.rb:

class Notifier < ActionMailer::Base
  default from: "\"Company Name\" <[email protected]>"

  default_url_options[:host] = Rails.env.production? ? 'domain.com' : 'localhost:5000'

  def welcome_email(user)
    @user = user
    mail to: @user.email, subject: "Thanks for signing up!"
  end

  ...

  def password_reset(user)
    @user = user
    @edit_password_reset_url = edit_password_reset_url(user.perishable_token)
    mail to: @user.email, subject: "Password Reset"
  end
end

Then for example, the password_reset mail is sent in my User model by doing...

user.rb:

def deliver_password_reset_instructions!
  reset_perishable_token!
  NotifierWorker.perform_async(self)
end

notifier_worker.rb:

class NotifierWorker
  include Sidekiq::Worker
  sidekiq_options queue: "mail"

  def perform(user)
    Notifier.password_reset(user).deliver
  end
end

So I guess I'm wondering a couple things here...

  1. Is it possible to define many "perform" actions in one single worker? By doing so I could keep things simple (one notifier/mail worker) as I have it and send many different emails through it. Or should I create many workers? One for each mailer (e.g. WelcomeEmailWorker, PasswordResetWorker, etc) and just assign them all to use the same "mail" queue with Sidekiq.
  2. I know it works as it is, but should I break out each of those mail methods (welcome_email, password_reset, etc) into individually mailer classes or is it ok to have them all under one class like Notifier?

Really appreciate any advice here. Thanks!

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about actionmailer