Ruby on rails 如何在UserMailer中添加before_过滤器来检查是否可以向用户发送邮件?
是否有一种全局方法可以为我的用户mailer编写一个before_过滤器,检查用户是否禁用了电子邮件?现在我所有的邮件都会检查用户的设置,这是非常多余的。我想用一个适用于所有邮递员的before_过滤器来干掉它Ruby on rails 如何在UserMailer中添加before_过滤器来检查是否可以向用户发送邮件?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,是否有一种全局方法可以为我的用户mailer编写一个before_过滤器,检查用户是否禁用了电子邮件?现在我所有的邮件都会检查用户的设置,这是非常多余的。我想用一个适用于所有邮递员的before_过滤器来干掉它 class UserMailer < ActionMailer::Base before_filter :check_if_we_can_mail_the_user .... private def check_if_we_can_mail_the_user
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
class UserMailer
可能吗?有人做过这样的事吗?谢谢,也许退房吧。看起来它可以做你想做的事。我没有做过这件事,但我用电子邮件拦截器做过类似的事情
class MailInterceptor
def self.delivering_email(message)
if User.where( :email => message.to ).first.mail_me != true
message.perform_deliveries = false
end
end
end
您将无法访问当前用户,因此您可以通过电子邮件找到该用户,该用户应已作为“收件人”字段出现在邮件对象中
有一个很好的Railscast负责设置电子邮件拦截器。
Rails 4已经有before\u filter和after\u filter回调。对于Rails3用户来说,添加它们非常简单:只需包含AbstractController::回调。这模仿了除了注释和测试之外,只包括回调的方法
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
classmymailer
我编辑了@naudster的答案以从消息中获取信息
class MyMailer < ActionMailer::Base
include AbstractController::Callbacks
after_filter :check_email
private
def check_email
if message.to.nil?
message.perform_deliveries = false
end
end
end
classmymailer
没有这样的事情,因为您通常会将这种逻辑放入fe中。用户模型。另一个问题是,在很多情况下,你发送邮件时都是异步的,而对于现代读者来说,没有“当前用户”这样的东西:Rails 4现在有邮件回调:在操作前,操作后,操作前后,不应该是“过滤前”吗?为什么是“after”?在before\u过滤器中没有@user
变量!而且邮件尚未送达。@Kulgar文档实际上解释说您可以同时使用这两种方法,但如果您使用after_filter,则可以根据在mailer方法上设置的实例变量生成逻辑:“您可以使用before_操作使用默认值、传递方法选项或插入默认标题和附件填充邮件对象。您可以使用after_操作来执行与before_操作类似的设置,但使用mailer操作中设置的实例变量。”(来源:)谢谢@sandre89:)