Using custom mime types
Posted by rick December 19, 2006 @ 03:02 AM
So, you’ve started using Rails’ new mime type support with responds_to, but you were wondering how to add your own custom types? Luckily, Geoffrey Grosenbach (aka topfunky) is there to show you the way. His example involves registering an extension for .png, and generating a custom icon for an order in his shopping cart with some RMagick-fu. His example looks something like this:
Mime::Type.register "image/png", :png
# then in your controller action
def show
respond_to do |format|
format.html { }
format.png { }
end
end
Mime::Type.register will add the image/png mime type to the collection of mime types, bind it to the .png extension. It also creates a special Mime::Type instance at Mime::PNG. Check out the great post and the comments for more tips on caching and RMagick.
Note: After some investigation, I’ve found that using Geoff’s :format hack is not required on Rails 1.2 if you make the request with the :format parameter. Using routes like formatted_post_path(@post, :xml) will give you a path like ”/posts/1.xml”. Accessing that will write public/posts/1.xml, regardless of what the page_cache_extension is.

I found a little tweaking was necessary to make this play nicely with template handlers registered with register_template_handler (specifically the rtex plugin). By default, rails seems to want to render the .rtex template even when a html page is requested. The work round I have is to override DEFAULT_BLOCKS[:html] in environment.rb to force the .rhtml template to be used. I also need to be careful not to have .rhtml and .rtex partials with the same name, otherwise the wrong ones may get loaded.
Are there any cleaner solutions?
That’s weird.
I’m using this technique with Markaby (.mab) and my own CSS template plugin and it works fine.
Is there a specific error, or does it just choose the wrong template?
http://code.whytheluckystiff.net/svn/markaby/trunk/init.rb
If you’re looking to add more mime types than the limited few that come with the library: http://www.eribium.org/?p=66
Sure, but why bother if you don’t use them?
Talking of generating images, this seemed a good place to announce Saucy, an unobtrusive styling framework. It uses RMagick to automatically render replacements for HTML elements specified in the page.
It’s available as a rails plugin, so it’s very nice and easy to get it up and running :)
Check it out here