Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Support catch-all format

Based on idea/patch by github.com/daicoden
  • Loading branch information...
commit ba3286f73955bc49678db95a79be2ab1b23c86b7 1 parent 9af4578
@mynyml authored
Showing with 39 additions and 5 deletions.
  1. +17 −5 lib/rack/respond_to.rb
  2. +22 −0 test/test_respond_to.rb
View
22 lib/rack/respond_to.rb
@@ -56,7 +56,7 @@ def included(base) #:nodoc:
# RespondTo::MediaType('htm') #=> 'text/html'
#
def MediaType(format)
- Rack::Mime.mime_type(format.sub(/^\./,'').insert(0,'.'))
+ Rack::Mime.mime_type(format.sub(/^\./,'').insert(0,'.'), media_types.first)
end
alias :MimeType :MediaType
@@ -91,17 +91,20 @@ def respond_to(&block)
module ClassMethods
# Allows defining different actions and returns the one which corresponds
- # to the highest ranking value in the RespondTo.media_types list.
+ # to the highest ranking value in the `RespondTo.media_types` list.
#
# If no handler is defined for the highest ranking value, respond_to will
- # cascade down the RespondTo.media_types list until it finds a match.
+ # cascade down the `RespondTo.media_types` list until it finds a match.
# Returns nil if there is no match.
#
# Wildcard media types (*/*, text/*, etc.) will trigger the first
# matching format definition, so order matters if you expect the Accept
# header to contain any (a nil Accept header, for instance, will be
- # turned into '*/*' as per rfc2616-sec14.1). Simply define the 'default'
- # handler first (usually html), and it will work like a charm.
+ # turned into '*/*' as per rfc2616-sec14.1).
+ #
+ # If `any` is specified as the format, it will behave as a catch-all and
+ # will match the highest ranking value in the `RespondTo.media_types` list
+ # if no previous format has.
#
# ===== Examples
#
@@ -154,6 +157,15 @@ module ClassMethods
# end
# #=> 'html'
#
+ # RespondTo.media_types = ['text/html', 'text/plain']
+ #
+ # respond_to do |format|
+ # format.xml { 'xml' }
+ # format.rss { 'rss' }
+ # format.any { 'unsusported format' }
+ # end
+ # #=> 'unsusported format'
+ #
def respond_to
format = Format.new
yield format
View
22 test/test_respond_to.rb
@@ -185,4 +185,26 @@ def setup
end
assert_equal nil, body
end
+
+ ## catch-all format
+
+ test "catch-all format" do
+ Rack::RespondTo.media_types = %w( text/html application/xml )
+
+ body = App.respond_to do |format|
+ format.txt { 'txt' }
+ format.avi { 'avi' }
+ format.any { 'any' }
+ end
+ assert_equal 'any', body
+ assert_equal 'text/html', Rack::RespondTo.selected_media_type
+
+ body = App.respond_to do |format|
+ format.htm { 'htm' }
+ format.xml { 'xml' }
+ format.any { 'any' }
+ end
+ assert_equal 'htm', body
+ assert_equal 'text/html', Rack::RespondTo.selected_media_type
+ end
end
Please sign in to comment.
Something went wrong with that request. Please try again.