Custom Mime Types for Beginners

Did you know that you can add Mime types (data types) to your Rails app to allow you to use the same URL for different response types?

For example, you might want to use your show method, e.g. /books/2,  with different responses depending on what MIME type you suggest.
html response – showing information about your book in html
json response – information about the book in json
pdf response – a pdf download about book 2
circus response – a specially formatted version of the books/2 data

The last one, ‘circus’, is obviously made up, but you CAN create new Mime types, called whatever you like. So you might want to make the data-type called ‘circus’ available and have a special format return on that URL when the data type is Circus.

All you need to do is

1.  Add the Mime type if it isn’t already there
In config/initializers/mime_types.rb add
Mime::Type.register "text/circus", :circus
(Since it is in an initializer, you will need to restart your server to pick up this change)

2. Make the response available in your controller action
def show
respond_to do |format|
format.html # render html
format.circus { #render circus }

3. Add the view you want
In your views folder,  you would put the circus template into a show.circus.erb file

4. Then in your request, set your data-type as ‘circus’ (E.g. in your form or Ajax request).


Leave a reply