Archive for June, 2011

When writing Crafting Rails Applications, I knew exactly which parts from Rails I wanted to talk about. However, I didn’t want the book to simply describe how everything works, I actually wanted everyone to build something useful from each part of Rails.

One of the hardest areas to come up with an useful tool as example was the template handlers. Template handlers are responsible for template compilation and the canonical examples are: ERb and Haml. Obviously, creating something like ERb or Haml from scratch would require a lot of code beyond the Rails integration so it wasn’t an option. On the other hand, tools that simply render rdoc or markdown templates would be too simple and there are already plenty of gems doing the same out there.

So I started playing with some options. The first one was something like Why’s Markaby but that would still require a good amount of code (albeit much less than ERb). Next, I have played with something called YERb (YAML + ERb) which was an interesting hack but too slow to be of any use. I was almost planning to remove the chapter about template handlers when it finally came to me the idea of markerb: markdown + erb (in the book, we did a wordplay and called merb). While the idea was simple and easy to implement, it had a great use case: multipart templates.

With Markerb, you can create one template for ActionMailer and it will be delivered both as text and HTML. So there is no need to maintain two templates. You write it in markdown, which is delivered as text, but also rendered to be delivered as HTML. Recently, I have crafted Markerb in its own gem so everyone can use it.

How to use?

The usage is quite simple. Assuming you have a notifier as below:

class Notifier < ActionMailer::Base
  def contact(recipient)
    @recipient = recipient
    mail(:to => @recipient, :from => "john.doe@example.com") do |format|
      format.text
      format.html
    end
  end
end

If you create a template at app/views/notifier/contact.markerb:

Multipart templates **rock**, right <%= @recipient %>?!

It will generate two parts, one in text and another in HTML when delivered. And that is it! Before we finish, here are a few things you might need to know:

  • The “contact.markerb” template should not have a format in its name. Adding a format would make it unavailable to be rendered in different formats;
  • The order of the parts matter. It is important for e-mail clients that you call format.text before you call format.html;
  • Notice you can normally use ERb inside the template.

If you are interested in how Markerb, template handlers and other part of Rails work, check out Crafting Rails Applications. We also hope to add a generator to Devise that will optionally copy all views as Markerb templates to your application.

And you? Do you have any use cases for Markerb? Do you have any other interesting template handlers you would like to share?