如何在 Sidekiq 中使用 Sorcery Gem

How to use Sorcery Gem with Sidekiq

我在 Rails 应用程序中使用 Sorcery Gem 对用户进行身份验证。一切正常。当用户注册时,我就可以发送用户激活电子邮件。但是发送电子邮件需要很长时间,所以我想延迟发送电子邮件或使用 Sidekiq 在后台发送电子邮件。我阅读了 Sorcery 文档,但找不到使用 Sidekiq 延迟电子邮件的方法。

请指导我如何使用 Sidekiq 延迟 Sorcery gem 发送的电子邮件。

可能有两种方法:

  1. 在 Mailer 中调用 Sidekiq worker
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

假设您有类似这样的代码(参考: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

你可以把代码改成这样

# 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

您的工作人员将根据 sidekiq 文档定义(参考: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:选项 1 不是一个干净的方法,但如果你坚持使用 Sorcery 遗留配置

  1. 不要为 srcoery 设置邮件设置(更简洁的方法)
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. 

我找到了解决方案。这很容易。我们只需要在 sorcery.rb 文件中添加以下行,所有魔法邮件将由 ActiveJob

处理
user.email_delivery_method = :deliver_later