From 0d0d46222cb87032e76bad42ef812b7ee7367873 Mon Sep 17 00:00:00 2001 From: David Heinemeier Hansson Date: Tue, 14 Aug 2012 22:09:43 -0500 Subject: Add Request#formats=(extensions) that lets you set multiple formats directly in a prioritized order --- .../lib/action_dispatch/http/mime_negotiation.rb | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'actionpack/lib/action_dispatch/http/mime_negotiation.rb') diff --git a/actionpack/lib/action_dispatch/http/mime_negotiation.rb b/actionpack/lib/action_dispatch/http/mime_negotiation.rb index e31f3b823d..0f98e84788 100644 --- a/actionpack/lib/action_dispatch/http/mime_negotiation.rb +++ b/actionpack/lib/action_dispatch/http/mime_negotiation.rb @@ -80,6 +80,27 @@ module ActionDispatch @env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])] end + # Sets the \formats by string extensions. This differs from #format= by allowing you + # to set multiple, ordered formats, which is useful when you want to have a fallback. + # + # In this example, the :iphone format will be used if it's available, otherwise it'll fallback + # to the :html format. + # + # class ApplicationController < ActionController::Base + # before_filter :adjust_format_for_iphone_with_html_fallback + # + # private + # def adjust_format_for_iphone_with_html_fallback + # request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/] + # end + # end + def formats=(extensions) + parameters[:format] = extensions.first.to_s + @env["action_dispatch.request.formats"] = extensions.collect do |extension| + Mime::Type.lookup_by_extension(extension) + end + end + # Receives an array of mimes and return the first user sent mime that # matches the order array. # -- cgit v1.2.3