How to use Sorcery Gem with Sidekiq

193 Views Asked by At

I am using Sorcery Gem to Authenticate user in my Rails application. Everything is working fine. When user register then I am able to send user activation email. However sending email is taking long time so I was thinking to delay the email or send email in backgroud using Sidekiq. I read Sorcery documentation but couldn't find the way to delay the email using Sidekiq.

Please guide me how to delay the email send by Sorcery gem using Sidekiq.

2

There are 2 best solutions below

0
r3b00t On BEST ANSWER

I found the solution. It's quite easy. We just need to add following line in sorcery.rb file and all sorcery mail will be handled by ActiveJob

user.email_delivery_method = :deliver_later
2
Abhinay On

There could be two approach to this:

  1. Call Sidekiq worker inside Mailer
what I understand from the docs is that you can configure it to call any
Mailer. What you could do inside the method is call 
MailerJob.perform_late(*arg) instead of calling mail(*args) right away

Assuming you have a code something like this (ref: https://github.com/Sorcery/sorcery/wiki/User-Activation)

# app/mailers/user_mailer.rb
def activation_needed_email(user)
  @user = user
  @url  = activate_user_url(@user.activation_token)
  mail(to: user.email, subject: 'Welcome to My Awesome Site')
end

You can change the code to this

# app/mailers/user_mailer.rb
def activation_needed_email(user)
  @user = user
  @url  = activate_user_url(@user.activation_token)
  # mail(to: user.email, subject: 'Welcome to My Awesome Site')
  MyMailerWorker.perfor_later(to: user.email, subject: 'Welcome to My Awesome Site')
end

Your worker would be defined as per the sidekiq docs(ref: https://github.com/mperham/sidekiq/wiki/Getting-Started)

class MyMailerWorker
  include Sidekiq::Worker

  def perform(to: nil, subject: nil)
    MailerIWantToCall.send_activation_email(to, subject)
  end
end

P.S: Option 1 is not a clean approach but works if you are stuck with Sorcery legacy configs

  1. Don't set mail settings for srcoery(A cleaner approach)
Do not setup mail through sorcery at all.You can revert the changes 
mentioned for UserMailer on this page
(github.com/Sorcery/sorcery/wiki/User-Activation) and add a callback on User 
model based on when do you want to trigger an email and that way you have 
control over what to call and with sidekiq or not.