Resise和Resque_mailer with Devise

时间:2013-01-11 21:04:45

标签: ruby-on-rails-3 devise resque

我正在使用resque_mailer gem(https://github.com/zapnap/resque_mailer)使用Resque实现后台电子邮件处理。除了Devise发送的电子邮件之外,我能够将它用于我的所有电子邮件。

我经历了一系列SO问题和博客文章(例如http://teeparham.posterous.com/send-devise-emails-with-resque),但找不到让它发挥作用的方法。

让resque_mailer与Devise合作需要遵循哪些准确的步骤?

2 个答案:

答案 0 :(得分:1)

我在网上浏览了tee's answer和一些资源,但无法找到可行的解决方案。

通过resque-mailer和设计代码阅读了几天之后,这个解决方案对我有用。感谢gist的发球台让我朝着正确的方向前进。

假设您的app/mailers/application_mailer.rb看起来类似于

class ApplicationMailer < ActionMailer::Base
  include Resque::Mailer # This will add a `self.perform` class method, which we will overwrite in DeviseResqueMailer
end

config/initializers/devise.rb

Devise.parent_mailer = "ApplicationMailer" 

Devise.setup do |config|
  config.mailer = 'DeviseResqueMailer'
end 

在使用devise的资源类中,覆盖send_devise_notification方法以发送资源类和id而不是object来防止编组

# app/models/user.rb
protected    
def send_devise_notification(notification, *args)
  # Based on https://github.com/zapnap/resque_mailer/blob/64d2be9687e320de4295c1bd1b645f42bd547743/lib/resque_mailer.rb#L81
  # Mailer may completely skip Resque::Mailer in certain cases - and will fail as we write custom handle in DeviseResqueMailer assuming mails are handled via resque
  # So in those cases, don't retain original devise_mailer so things work properly
  if ActionMailer::Base.perform_deliveries && Resque::Mailer.excluded_environments.exclude?(Rails.env.to_sym)
    # Originally devise_mailer.send(notification, self, *args).deliver
    # Modified to ensure devise mails are safely sent via resque
    resource_id, resource_class = self.id, self.class.name
    devise_mailer.send(notification, {resource_id: resource_id, resource_class: resource_class}, *args).deliver
  else
    super
  end
end

最后,在app/mailers/devise_resque_mailer.rb中,再次从数据库中获取记录并继续

class DeviseResqueMailer < Devise::Mailer

  def self.perform(action, *args)
    # Hack to prevent RuntimeError - Could not find a valid mapping for admin.attributes
    record_hash = args.shift
    record = record_hash["resource_class"].constantize.find(record_hash["resource_id"])
    args.unshift(record)
    super # From resque-mailer
  end
end

我觉得这种方法比使用devise-async更好,因为所有邮件都经过相同的代码路径。如果需要,它更容易控制和覆盖。

答案 1 :(得分:0)

我看看设计 - 异步。看起来它适合您的用例。 Devise Async