如何在UserMailer中添加一个before_filter来检查是否可以邮寄用户?

有没有一种全局的方式我可以为我的用户邮件程序编写一个before_filter,检查用户是否禁用了电子邮件? 现在我的每个邮件都检查用户的设置,这是非常多余的。 我想通过一个适用于所有邮件程序的before_filter来干这个问题。

class UserMailer < ActionMailer::Base before_filter :check_if_we_can_mail_the_user .... private def check_if_we_can_mail_the_user if current_user.mail_me == true #continue else Do something to stop the controller from continuing to mail out end end end 

可能? 有没有人做过这样的事情? 谢谢

Rails 4已经有before_filter和after_filter回调。 对于Rails 3用户来说,添加它们非常简单:只需包含AbstractController :: Callbacks。 这模仿了Rails 4的变化 ,除了评论和测试之外,还包括Callbacks。

 class MyMailer < ActionMailer::Base include AbstractController::Callbacks after_filter :check_email def some_mail_action(user) @user = user ... end private def check_email if @user.email.nil? mail.perform_deliveries = false end true end end 

我没有这样做,但我用电子邮件拦截器完成了类似的事情。

 class MailInterceptor def self.delivering_email(message) if User.where( :email => message.to ).first.mail_me != true message.perform_deliveries = false end end end 

您将无法访问current_user,因此您可以通过电子邮件找到该用户,该用户应该已经在邮件对象中作为“收件人”字段。

有一个很好的Railscast覆盖设置电子邮件拦截器。 http://railscasts.com/episodes/206-action-mailer-in-rails-3?view=asciicast

也许请查看https://github.com/kelyar/mailer_callbacks 。 看起来它会做你想要的。