Using custom mime types

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.

blog comments powered by Disqus