【问题标题】:Rails 5 - Best way to prevent emails from being sent to unsubscribed usersRails 5 - 防止电子邮件发送给未订阅用户的最佳方法
【发布时间】:2020-05-05 20:24:14
【问题描述】:

我正在使用 Rails 5。

我有一个 Affiliate 模型,具有布尔属性 email_notifications_on

我正在为附属机构构建一个非常强大的电子邮件滴灌系统,但我不知道在发送电子邮件之前检查附属机构是否有电子邮件通知的最佳位置。

我的大部分电子邮件都是从 Resque BG 工作发送的,还有一些是从控制器发送的。

以下是我如何检查 BG 作业的订阅状态的示例:

class NewAffiliateLinkEmailer

  @queue = :email_queue

  def self.perform(aff_id)

    affiliate = Affiliate.find(aff_id) 

    if affiliate.email_notifications_on?
      AffiliateMailer.send_links(affiliate).deliver_now
    end

  end
end

似乎在 10 多个区域中写 if affiliate.email_notifications_on? 不是正确的方法,特别是如果我将来需要满足另一个条件。或者这样可以吗?

我认为AffiliteMailer 中的某种回调可能会起作用,但看到很多人建议不要在 Mailer 中使用业务逻辑。

任何想法/建议将不胜感激。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 actionmailer


    【解决方案1】:

    说实话,我认为没有比在Affiliate模型中创建方法更好的方法了,

    def should_send_email?
      # all business logic come here
      # to start with you will just have following
      # email_notifications_on?
      # later you can add `&&` or any business logic for more conditions
    end
    

    您可以使用此方法代替属性。它更具可重用性和可扩展性。您仍然必须在每次调用中使用该方法。如果你喜欢单行,那么你可以使用 lambda。

    【讨论】:

      猜你喜欢
      • 2019-12-08
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-30
      • 2011-10-02
      • 1970-01-01
      • 2011-02-25
      相关资源
      最近更新 更多