Skip to content
This repository
Browse code

Add Request#formats=(extensions) that lets you set multiple formats d…

…irectly in a prioritized order
  • Loading branch information...
commit 0d0d46222cb87032e76bad42ef812b7ee7367873 1 parent 6f7b651
David Heinemeier Hansson authored
16  actionpack/CHANGELOG.md
Source Rendered
... ...
@@ -1,5 +1,19 @@
1 1
 ## Rails 4.0.0 (unreleased) ##
2 2
 
  3
+*   Add Request#formats=(extensions) that lets you set multiple formats directly in a prioritized order *DHH*
  4
+
  5
+    Example of using this for custom iphone views with an HTML fallback:
  6
+
  7
+      class ApplicationController < ActionController::Base
  8
+        before_filter :adjust_format_for_iphone_with_html_fallback
  9
+      
  10
+        private
  11
+          def adjust_format_for_iphone_with_html_fallback
  12
+            request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
  13
+          end
  14
+      end
  15
+
  16
+
3 17
 *   Add Routing Concerns to declare common routes that can be reused inside
4 18
     others resources and routes.
5 19
 
@@ -28,7 +42,7 @@
28 42
 
29 43
         resources :posts, concerns: [:commentable, :image_attachable]
30 44
 
31  
-    *David Heinemeier Hansson + Rafael Mendonça França*
  45
+    *DHH + Rafael Mendonça França*
32 46
 
33 47
 *   Add start_hour and end_hour options to the select_hour helper. *Evan Tann*
34 48
 
21  actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -80,6 +80,27 @@ def format=(extension)
80 80
         @env["action_dispatch.request.formats"] = [Mime::Type.lookup_by_extension(parameters[:format])]
81 81
       end
82 82
 
  83
+      # Sets the \formats by string extensions. This differs from #format= by allowing you
  84
+      # to set multiple, ordered formats, which is useful when you want to have a fallback.
  85
+      #
  86
+      # In this example, the :iphone format will be used if it's available, otherwise it'll fallback
  87
+      # to the :html format.
  88
+      #
  89
+      #   class ApplicationController < ActionController::Base
  90
+      #     before_filter :adjust_format_for_iphone_with_html_fallback
  91
+      #
  92
+      #     private
  93
+      #       def adjust_format_for_iphone_with_html_fallback
  94
+      #         request.formats = [ :iphone, :html ] if request.env["HTTP_USER_AGENT"][/iPhone/]
  95
+      #       end
  96
+      #   end
  97
+      def formats=(extensions)
  98
+        parameters[:format] = extensions.first.to_s
  99
+        @env["action_dispatch.request.formats"] = extensions.collect do |extension|
  100
+          Mime::Type.lookup_by_extension(extension)
  101
+        end
  102
+      end
  103
+
83 104
       # Receives an array of mimes and return the first user sent mime that
84 105
       # matches the order array.
85 106
       #

0 notes on commit 0d0d462

Please sign in to comment.
Something went wrong with that request. Please try again.