[英]Rails - Send all emails with delayed_job asynchronously
我正在使用delayed_job ,我對此非常滿意(特別是對於無用的擴展)。
但是我想設置來自我的應用程序的所有郵件都是異步發送的。
實際上,為郵寄者提供了解決方案
# without delayed_job
Notifier.signup(@user).deliver
# with delayed_job
Notifier.delay.signup(@user)
不適合我,因為:
我可以使用這種擴展https://github.com/mhfs/devise-async但我寧願一次找出整個應用程序的解決方案。
我不能擴展ActionMailer
來覆蓋.deliver
方法(就像這里https://stackoverflow.com/a/4316543/1620081但它已經4年了,就像我在這個主題上找到的幾乎所有文檔一樣)?
我正在使用帶有activerecord的Ruby 1.9和Rails 3.2。
感謝你的支持
一個簡單的解決方案是在Notifier對象上編寫實用程序方法,如下所示:
class Notifier
def self.deliver(message_type, *args)
self.delay.send(message_type, *args)
end
end
發送注冊電子郵件如下:
Notifier.deliver(:signup, @user)
該實用方法提供單點,如果需要,您可以使用resque或sidekiq解決方案替換延遲的作業。
如果你有你的ActiveJob和並發庫建立完成文檔在這里 。最簡單的辦法是重寫參與交易的郵件你設備send_devise_notification實例方法,如顯示這里
class User < ApplicationRecord
# whatever association you have here
devise :database_authenticatable, :confirmable
after_commit :send_pending_devise_notifications
# whatever methods you have here
protected
def send_devise_notification(notification, *args)
if new_record? || changed?
pending_devise_notifications << [notification, args]
else
render_and_send_devise_message(notification, *args)
end
end
private
def send_pending_devise_notifications
pending_devise_notifications.each do |notification, args|
render_and_send_devise_message(notification, *args)
end
pending_devise_notifications.clear
end
def pending_devise_notifications
@pending_devise_notifications ||= []
end
def render_and_send_devise_message(notification, *args)
message = devise_mailer.send(notification, self, *args)
# Deliver later with Active Job's `deliver_later`
if message.respond_to?(:deliver_later)
message.deliver_later
# Remove once we move to Rails 4.2+ only, as `deliver` is deprecated.
elsif message.respond_to?(:deliver_now)
message.deliver_now
else
message.deliver
end
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.