ruby-on-rails - 如何在 UserMailer 中添加一个 before_filter 来检查是否可以向用户发送邮件?

标签 ruby-on-rails ruby-on-rails-3

是否有一种全局方式可以为我的用户邮件程序编写 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

关于ruby-on-rails - 如何在 UserMailer 中添加一个 before_filter 来检查是否可以向用户发送邮件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8594626/

相关文章:

ruby-on-rails - 事件模型在机架测试期间发送验证错误两次。

ruby-on-rails-3 - 在 webapp 中实现管理员的推荐方法是什么

ruby-on-rails - 在 rails 中创建大标签

ruby-on-rails - 在 Rails 中创建 Action

ruby-on-rails - before_save 如果 attribute.present?

mysql - 在 Rails 中迭代执行结果的结果

ruby-on-rails - Controller Spec#Show Action : exoected: [Object], 得到:无错误 - RSpec 3

html - 使用 Bootstrap 和 Rails 让 HTML <body> 填充整个垂直空间?

ruby-on-rails - 具有不同仪表板的多个设计用户

ruby-on-rails - Rails3 和 Devise 作为基本 CRM 的一部分