在我的Rails应用程序中,我想暂时停止为特定用户发送电子邮件(例如,当我因配额而退款时),直到用户确认他能够再次收到电子邮件。
我有一个适用于所有邮件程序类的公共超类。我总是在发送邮件之前调用方法setup_email
。
致电@user.mail_suspended?
的最佳地点在哪里?
这是一些简化的示例应用程序,我使用Rails 2.3:
# Common super class for all Mailers
class ApplicationMailer < ActionMailer::Base
protected
def setup_mail(user)
@recipients = user.email
@from = ...
end
end
# Specific Mailer for User model
class UserMailer < ApplicationMailer
def message(user, message)
setup_mail(user)
@subject = "You got new message"
@body[:message] = message
end
end
# Use the UserMailer to deliver some message
def MessagesController < ApplicationController
def create
@message = Message.new(params[:message])
@message.save
UserMailer.deliver_message(@message.user, @message)
redirect_to ...
end
end
答案 0 :(得分:1)
我通过将ActionMailer::Base.perform_deliveries
设置为false来解决此问题:
def setup_mail(user)
email = user.default_email
if email.paused?
ActionMailer::Base.perform_deliveries = false
logger.info "INFO: suspended mail for #{user.login} to #{email.email})"
else
ActionMailer::Base.perform_deliveries = true
end
# other stuff here
end
答案 1 :(得分:1)
我尝试了很多方法,但除了这个没有人能帮我。
class ApplicationMailer < ActionMailer::Base
class AbortDeliveryError < StandardError; end
before_action :ensure_notifications_enabled
rescue_from AbortDeliveryError, with: -> {}
def ensure_notifications_enabled
raise AbortDeliveryError.new unless <your_condition>
end
...
end
standardError
继承类以引发异常。空的 lambda 导致 Rails 6 只返回一个 ActionMailer::Base::NullMail 实例,它不会被传递 (就像你的邮件方法没有调用邮件一样,或者返回 过早)。
答案 2 :(得分:0)
我不会普遍设置perform_deliveries,只是根据消息,例如
after_filter :do_not_send_if_old_email
def do_not_send_if_old_email
message.perform_deliveries = false if email.paused?
true
end