Hi everyone, just wanna share a way on how to add callbacks for your
ActionMailer. I know most of you guys are already familiar with this trick, but then if you want to share other tricks... you may do so. I'm also curious to know other alternatives.
First, why do we want to do this?
Basically, you will be needing callbacks for ActionMailer if you want an action to happen before or after the email delivery.
Thinking about using...
Well, that's exactly what we want.
If we use that in our Mailer Class... obviously the error would be like this:
Because, the inherited superclass is the ActionMailer::Base.
What we need to do is to properly include the Controller Callbacks Helper to make the callback filtering work.
In this example, I want to insert data into my Email model after the account confirmation email delivery...
after means we have to use the after_filter
In my User model, I have of course an after_create action that will deliver the account confirmation email
class User < ActiveRecord::Base after_create :creation_confirmation_email private def creation_confirmation_email if email.present? UserMailer.account_create_confirmation(self).deliver end end end
Here's the UserMailer class:
class UserMailer < ActionMailer::Base include AbstractController::Callbacks def account_create_confirmation(user) I18n.locale = 'pt' @user = user mail(from: 'firstname.lastname@example.org', to: @user.email, subject: 'Welcome to Xiruki Site') do |format| format.text format.html end end private def audit_users_email @subject = message.subject @body = message.body.encoded audit = Email.create!( subject: @subject, email: @user.email, first_name: @user.first_name, last_name: @user.last_name, body: @body) end end
From the code above, notice that I included the Controller Callbacks Helper at the top!
And then, I included the after_filter next to it.
In this case, you can also use [:only, :except] params because you have already included the Helper that will recognize those.
after_filter :audit_users_email, only: [:password_reset, :account_confirmation]
That's all! Hope it helps!
Additionally, I think there's also a gem for this kind of scenario! But I am not sure if this is still working: actionmailer-callbacks gem
And a documented document in Ruby on Rails site about after_action and before_action
I've tried those, but it didn't work on my behalf. If you already used those callback actions then you may also share your experience(s) in this thread.
Another thing is using Mailer Observer that I've seen from this thread...
Haven't still tried Observers for Mailers.. but I would give a feedback whenever it's possible.
That's all. Happy Callback!