greggreg
greggreg

Reputation: 12085

rails 3.1: Where to filter out email addresses that have opted out

Trying to figure out the cleanest way prevent sending email to users who have opted out from receiving them in rails 3.1.

I was thinking about overriding Mail.deliver to check the db and determine if the recipients are unsubscribed or not, then conditionally delivering the email.

That seems like the least intrusive way to go about it, but requires creating the Mail objects that are never going to be sent.

Seems like the most resource conscious way would be to do the check in the controller, thus preventing the Mail objects that are never going to be sent from the burden of existence.

This though seems more intrusive and prone to developers forgetting to make the check when creating new mailers.

Is there a standard practice for this situation?

** edit ** This is for managing a collection of users who have opted out of receiving notifications, rather than something like managing subscriptions to a news letter.

Upvotes: 1

Views: 491

Answers (1)

jefflunt
jefflunt

Reputation: 33954

If the attribute that determines whether or not to get email notifications is just a field on a model in the DB, you could create a named scope called something like 'want_email_notifications' to get all the users that have subscribed.

So, if you have a User class, and that class has an attribute called opt_out, then you could do something like:

class User < ActiveRecord::Base

  named_scope :want_email_notifications, :conditions => ['opt_out = ?', false]

  ...
end

Then, to call it, you do User.want_email_notifications, which gives you an array of all User objects that want email notifications.

Then, when you're checking whether or not a given user should receive an email notification, write a condition similar to:

send_email_notification(user_in_question) if User.want_email_notifications.include?(user_in_question)

In this example, send_email_notification is the method where you would call the associated delivery method, which actually sends the email.

Upvotes: 2

Related Questions