I'd like to execute some kind of before filter in my ActionMailer
class... does anyone know how to do this?
Specifically I let my users turn off email notifications, and I'd like
to check their notification settings before any email gets sent. Seems
like the wrong thing to do to have a million if statements lying all
over the place whenever emails are delivered...
You would be better off asking your users model for a list of people
to send to who are subscribed.
Your mailer part of the app has to find the user to get the email
address, just set up a custom finder in the user model that refuses to
give out the user object to the mailer if the user has unsubscribed on
their record.
Ususally when I send an email I already have the user object in my
hand (most of my emails are for things like watchlist changes,
questions from other users, etc.), so an if statement to check whether
the user wants to receive emails would be a lot cheaper than doing
another database query.
What about inside the mailer methods? can I return false or throw an
exception and be sure that the email won't be delivered? Is there any
way to control whether the email is delivered from inside the mailer
object instead of relying on the caller?
Ususally when I send an email I already have the user object in my
hand (most of my emails are for things like watchlist changes,
questions from other users, etc.), so an if statement to check whether
the user wants to receive emails would be a lot cheaper than doing
another database query.
Well, if you have done a @user = User.find(123) then doing
@user.wants_email? shouldn't generate another DB query as it should
hit the ActiveRecord cache.
Why can't you just do:
deliver_email if @user.subscribed
and have a boolean value in your table called "subscribed"
I think that would be about as clean and dry as can be.
If you want to put it in your create_email method, you will have to
make a method in your Notifier that creates the email but checks the
users subscription status first....
Yeah thanks Mikel, that's what I ended up doing in the end. I created
new methods in my mailer class that check to see if the user wants to
be sent emails, if so then it's sent, otherwise it's stored in a
messages table that the user can check next time they sign into the
website.