Search code examples
ruby-on-railsruby-on-rails-5actionmailer

Rails 5 - Best way to prevent emails from being sent to unsubscribed users


I am using Rails 5.

I have an Affiliate model, with a boolean attribute email_notifications_on.

I am building a quite robust email drip system for affiliates and can't figure out where the best place is to check if the affiliate has email notifications on before delivering the email.

Most of my emails are being sent from Resque BG jobs, a few others from controllers.

Here is an example of how I am checking the subscribe status from a BG job:

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

It seems like writing if affiliate.email_notifications_on? in 10+ areas is not the right way to do this, especially if I need another condition to be met in the future. Or is this fine?

I thought maybe some sort of callback in the AffiliteMailer would work, but saw many people advising against business logic in the Mailer.

Any thoughts/advice would be appreciated.


Solution

  • To be honest, I don't think any better way than creating a method in Affiliate model as follows,

    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
    

    You can use this method instead of the attribute. It is more re-usable and extendable. You will still have to use the method in every call. If you like single liners then you can use lambda.