Using ActionMailer layouts with Clearance
2009/09/11 // Leeds // // Feed
If you’re building a Rails application thats going to be sending a lot of emails, chances are you’re going to want to have a consistent layout between each. You use layouts within your application so why not use them in your mailers? Since commit e9a8e0053be3b293ab89fb584f1d660063f107aa you’ve been able to use layouts within your mailers, making it easy to implement a consistent email format across all emails.
You use them just like normal rails layouts, i tend to explicitly declare the mailer layout at the top of my mailer class. More specifically i usually declare a base mailer class to use as the parent class for all my other mailers, making setting up and configuring each mailer really easy, heres what mine looks like:
# app/models/base_mailer.rb
class BaseMailer < ActionMailer::Base
layout "mailer"
default_url_options[:host] = HOST # set in development/staging/production.rb
protected
def setup_mail(email)
from DO_NOT_REPLY # set in development/staging/production.rb
recipients email
subject "[My Mailer] "
sent_on Time.now
end
end
Then my object specific mailer:
# app/models/enquiry_mailer.rb
class EnquiryMailer < BaseMailer
def after_create(enquiry)
setup_mail(enquiry.email)
@subject += "Thanks for contacting us."
@body = { :name => enquiry.name }
end
end
I, like a lot of people use Clearance, an authentication engine written by the guys from Thoughtbot. Obviously you want to take advantage of the same mailer layouts within the Clearance mailers too, so lets tweak the ClearanceMailer class to tell it about the layout:
# config/initializers/apply_clearance_mailer_layout.rb
ClearanceMailer.class_eval { layout "mailer" }
This performs a class_eval, modifying the class when the application initialises to use the mailer layout we’re using in the rest of our application. If you’re sending a lot of mails it pays off to keep them all consistent, as sometimes this is the first port of call for your client/customer.