有没有一种全局方法可以为用户邮件程序编写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。这类似于change to Rails 4,除了注释和测试外,仅包括回调。
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。看起来它会做您想要的。
我编辑了@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