Using Markdown for Email Templates in Rails

I’ve been working on a Rails freelance project that has a lot of email templates. For the last year, I’ve had two versions of each template–an HTML template and a text template. For a welcome email, I had both welcome.html.erb and welcome.text.erb. The worst part about this setup is that when you need to make a change to the email, you need to change two files. This isn’t very DRY, so I finally went in search of a better way to do this.
I found several StackOverflow questions that helped me get to my current solution. If you’re interested in the context, here they are:

Markerb gem

Using Markdown seemed like a great solution, so I started digging into the Markerb gem. This gem, combined with a parser (I’m using the recommended Redcarpet), allows you to write just one email template–in my case, welcome.markerb. Using standard Markdown format, I now only have to manage a single template, which is then parsed into both the text part and HTML part when the email gets sent.

Once you add Markerb to your Gemfile and run the bundle command, all you need to change is the extension on your template file and then reformat your templates to use Markdown. Nothing changes in your ActionMailer. When Rails goes looking for the template, Markerb takes over, parses the file, and spits out the text and HTML parts that get sent out.

Leave a Reply