Skip to content

Migrating to Sidekiq::Mailer

Anderson Dias edited this page Aug 29, 2014 · 1 revision

There are few changes you need to do in your mailers to use Sidekiq::Mailer asynchronous magic :)

Probably you are using something like:

class SubscriptionMailer < ActionMailer::Base
  def welcome(user)
    ...
  end
end

SubscriptionMailer.welcome(user).deliver

When you want to migrate this mailer to be asynchronous you need to keep one thing in mind: Sidekiq persists arguments to Redis, use simple identifiers instead of complex objects.

Sidekiq uses JSON.dump to send data do Redis, so, as the it's documentation says:

[args] must be composed of simple JSON datatypes: string, integer, float, boolean, null, array and hash.

Instead of passing a User object, you need to pass a identifier like an id or email, and fetch it from the database inside your mailer action.

So, before adding include Sidekiq::Mailer to your mailer you need to reimplement it's external interface.

Your code should look something like:

class SubscriptionMailer < ActionMailer::Base
  include Sidekiq::Mailer

  def welcome(user_id)
    user = User.find(user_id)
    ...
  end
end

SubscriptionMailer.welcome(user.id).deliver

It's a simple change, but sometimes it needs some work to replace every mailer call in your application. That's the tradeoff of using async processing, but I think it's worth to be done.

Clone this wiki locally