Organizing Mailer Templates with prepend_view_path in Rails.
Table of Contents
If you're using multiple mailers in your Rails app, you know the struggle: email templates are scattered throughout your app/views directory. Each mailer has its own folder, and it's easy to lose track of where everything is. Enter prepend_view_path
– a simple yet powerful way to organize all your mailer templates in one central location.
The Problem
By default, Rails looks for mailer templates in directories like app/views/user_mailer/
, app/views/notification_mailer/
, app/views/order_mailer/
etc.
This structure works, but it mixes mailer templates with your regular web view templates.
The Solution: prepend_view_path
Luckily, Rails has a simple splution for this. With prepend_view_path
, you can tell Rails to look in a different directory first for templates:
class ApplicationMailer < ActionMailer::Base
prepend_view_path "app/views/mailers"
end
New Directory Structure
Now you can organize all your mailer templates in a separate directory:
app/
views/
mailers/
user_mailer/
welcome.html.erb
password_reset.html.erb
notification_mailer/
daily_summary.html.erb
order_mailer/
confirmation.html.erb
# Regular view templates stay here
users/
products/
Conclusion
prepend_view_path
is a small feature with a big impact. Similar to the idea how namespaces work in Rails, it helps keep your code cleaner and more organized – especially in larger Rails applications with many different email templates. It's one of the few architectural changes that we implement in every Rails application that we work on. It's better than the default. Give it a try and bring some order to your mailers!