Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
RESTful Rails | 219

New MIME types can be registered withMime::Type.register. This method takes
four arguments: the primary MIME type, the Rails shortcut, a set of synonym MIME
types (such astext/x-jsonfor JSON text), and a set of synonym file extensions, used
to force a format where the client does not send anAcceptheader or sends an
improper one.


The Rails shortcut symbol, such asrss, is also taken to be a file exten-
sion; a request URI ending in.rsswill trigger aformat.rssblock. The
list of synonym extensions adds to this default extension.

For example, suppose we want to add JPEG format support to an application. We
would like to writeformat.jpgin arespond_toblock to render a JPEG response. This
requires mapping thejpgformat type to theimage/jpegtype, as well as thejpgand
jpegextensions. We can do this by simply putting the following in ourconfig/
initializers/mime_types.rb:


Mime::Type.register "image/jpeg", :jpg, [], %w(jpeg)

HTTP Caching


Earlier in the chapter, we discussed HTTP’s use of conditionalGETfor client-side
caching. Under conditionalGET, the client requests a resource along with an identi-
fier of the client’s latest copy, so the server doesn’t have to send a resource that the
client already has.


One of the most important parts of caching is inexpensively figuring out the identity
of a given entity. In order to determine whether an entity is stale, you must compare
its content with the canonical version on the server. One trivial way to do this would
be to generate and compare the entire response body, but this is ridiculous. It saves
no bandwidth, CPU time, or I/O. We need a shorter way to identify an entity.


The HTT Pstandard provides for Entity Tags (usually calledETags, after the HTTP
header in which they are provided), which serve to identify the resource that they
are attached to. You can compare two resources by comparing their ETag. This is
used with conditionalGET, where the client sends the ETag associated with its latest
version in anIf-None-Matchheader. The server compares this ETag with that of its


xml application/xml, text/xml, application/x-xml
rss application/rss+xml
atom application/atom+xml
yaml application/x-yaml, text/yaml
multipart_form multipart/form-data
url_encoded_form application/x-www-form-urlencoded
json application/json, text/x-json

Shortcut MIME types
Free download pdf