Wednesday, October 31, 2007

Adding Mime Types to Merb

Adding a new mime type in Merb is really simple. It's just one line.

Lets say we want the following:

  • .pdf extension to be associated with the :pdf content_type

  • Want to call to_pdf on an object we give to render

  • Content-Type: application/pdf

  • Content-Encoding: gzip

For all this we just make a call to Merb.add_mime_type.
The arguments to Merb.add_mime_type are

  1. Symbol for content_type

  2. Symbol of method to call to convert an object to this format

  3. An array of possible content types that the browser might give the server for this format. The first one will be used as the outgoing Content-Type header

  4. A hash of response headers you want to include [optional]

To write add our pdf mime type we would put the following into merb_init.rb down the bottom.
Merb.add_mime_type(:pdf, :to_pdf, %w[application/pdf], "Content-Encoding" => "gzip")

That's it. Now in your controllers you can use
provides :pdf
# and then
render @obj
and to_pdf will be called on @obj.

This looks like a great opportunity to use a presenter object with a to_pdf method on it.

If there's a format that you never want to use a transform method on, since you'll always have templates for them, just use nil for the transform method.