Read more

Rails 2: Refuse response formats application-wide

Dominik Schöler
April 28, 2014Software engineer at makandra GmbH

If you regularly get ActionView::MissingTemplate exceptions, maybe some bot visits your site requesting silly formats like:

http://www.rails-app.com/makandra.html-username-2000 # => Rails tries to retrieve 'makandra' with format 'html-username-2000'
Illustration web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
Read more Show archive.org snapshot

Just restrict accepted format parameters for the whole application like this:

class ApplicationController < ActionController::Base

  before_filter :refuse_silly_formats

  private

  def refuse_silly_formats
    acceptable_formats = %w[html xml pdf]

    if params[:format]
      unless acceptable_formats.include? params[:format].downcase
        Rails.logger.error "Format not supported: #{params[:format]}"
        head interpret_status(:not_acceptable)
      end
    end
  end

end

Note: request.format more reliably tells the format, but includes Rails-required formats such as application/x-www-form-urlencoded (which we must not refuse). For our purposes, getting the format from the params is exactly what we need. You may also skip that before_filter Show archive.org snapshot for a certain controller/action.

Kudos to Peter Wagenet Show archive.org snapshot .

Posted by Dominik Schöler to makandra dev (2014-04-28 10:27)