Rails Editable Mail Templates w/Preview from 37Signals

Back | rails, ruby | 9/15/2011 |

Last time we added custom editable mail templates to our mailers and made them Markdown format [read first]. Awesome. Lets add a preview to the templates with 37-signals mail_view. I don’t know how we lived without this before!

Gemfile

  1. gem "mail_view", :git => "https://github.com/37signals/mail_view"

Routes

Remember how we pre-declared our mailers in a hash. This is going to come in handy for config/routes.rb.

  1. Mailers::ALL.each_pair do |klass, method_names|
  2.   mount "#{klass.gsub('::', '')}::Preview".constantize => "mail_templates/#{klass.underscore}/preview"
  3. end

Now we have a mail_templates/devise/mailer/preview/reset_password_instructions path for a Devise::Mailer mailer!

Preview

This needs to route somewhere. Lets add a preview into our overridden DeviseMailer.

  1. class DeviseMailer < Devise::Mailer
  2.  
  3.   def template_paths
  4.     "devise/mailer"
  5.   end
  6.   
  7.   def devise_mail(record, action)
  8.     ...
  9.   end
  10.   
  11.   class Preview < MailView
  12.  
  13.     def invitation_instructions
  14.       DeviseMailer.devise_mail(
  15.         User.new({email: 'chuck@example.com',
  16.             name: 'Chuck Norris',
  17.             invitation_token: 'invitation-token'}),
  18.         :invitation_instructions)
  19.     end
  20.  
  21.   end
  22.  
  23. end

Why Chuck Norris? I’ve been enjoying the Chuck Norris Jenkins Plugin too much lately. Chuck Norris can preview mail templates in PDF!

Here’s our mail templates admin page with a link to the preview (mail_templates/index.html.haml).

  1. %h1 Mail Templates
  2.  
  3. %table
  4.   %tr
  5.     %th Class Name
  6.     %th Method Name
  7.     %th Subject
  8.     %th
  9.     %th
  10.  
  11.   - @mail_templates.each do |mail_template|
  12.     %tr
  13.       %td= mail_template.class_name
  14.       %td= mail_template.method_name
  15.       %td= mail_template.subject
  16.       %td.admin_actions= link_to 'Edit', edit_mail_template_path(mail_template)
  17.       %td.admin_actions= link_to 'Preview',
  18.         "/admin/mail_templates/#{mail_template.class_name.underscore}/preview/#{mail_template.method_name}",
  19.         :target => '_blank'

Well, that’s it. You need to add a Preview class for every mailer.

Screenshot

reset-password