воскресенье, 1 сентября 2013 г.

Returning 406 error with Rails

On page http://mysite/posts.blah i get 200 OK because Rails does not think that is wrong file extension.
If you want to close this pages with 406 error, you can do something like:

in ApplicationController: 
class ApplicationController < ActionController::Base
  ...
  before_filter :check format
  ...
  def check_format
    unless (Mime::EXTENSION_LOOKUP.values << Mime::ALL).include?(request.format)
      render file: 'public/404.html', layout: false, status: 406
    end
  end
  ...
end
Mime::EXTENSION_LOOKUP returns hash of all mime types registred in your app. In my case:
irb> Mime::EXTENSION_LOOKUP
{"html"=>text/html, "xhtml"=>text/html, "text"=>text/plain, "txt"=>text/plain, "js"=>text/javascript, "css"=>text/css, "ics"=>text/calendar, "csv"=>text/csv, "png"=>image/png, "jpeg"=>image/jpeg, "jpg"=>image/jpeg, "jpe"=>image/jpeg, "gif"=>image/gif, "bmp"=>image/bmp, "tiff"=>image/tiff, "tif"=>image/tiff, "mpeg"=>video/mpeg, "mpg"=>video/mpeg, "mpe"=>video/mpeg, "xml"=>application/xml, "rss"=>application/rss+xml, "atom"=>application/atom+xml, "yaml"=>application/x-yaml, "multipart_form"=>multipart/form-data, "url_encoded_form"=>application/x-www-form-urlencoded, "json"=>application/json, "pdf"=>application/pdf, "zip"=>application/zip, "xlsx"=>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, "printable"=>text/html}
last two - my mime types from config/initializers/mime_types.rb initializer

Don't forget to set request header for ajax, by default it "*/*" (Mime::ALL).
Also this type commonly used by different statistics collectors and seo tools.

We add this mime type to list of allowed in this part:
Mime::EXTENSION_LOOKUP.values << Mime::ALL
but it's a good practise to use right headers in your requests.
In application.js.coffee:
  $.ajaxSetup
    beforeSend: (xhr) ->
      xhr.setRequestHeader("Accept", "application/json")

And this in ajax requests for example if you use async loading of some heavy html partials:
beforeSend: (xhr) ->
  xhr.setRequestHeader("Accept", "text/html")

To read:
How to limit the resource formats in the Rails routes file
Mime module api
Mime Type Resolution in Rails (Case 3)

Комментариев нет:

Отправить комментарий