Skip to content

Commit

Permalink
Add ignore_accept_header config to AD::Request.
Browse files Browse the repository at this point in the history
  • Loading branch information
josevalim committed May 2, 2011
1 parent 79a9beb commit 73c94ed
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
27 changes: 22 additions & 5 deletions actionpack/lib/action_dispatch/http/mime_negotiation.rb
@@ -1,6 +1,13 @@
module ActionDispatch
module Http
module MimeNegotiation
extend ActiveSupport::Concern

included do
mattr_accessor :ignore_accept_header
self.ignore_accept_header = false
end

# The MIME type of the HTTP request, such as Mime::XML.
#
# For backward compatibility, the post \format is extracted from the
Expand Down Expand Up @@ -42,16 +49,14 @@ def format(view_path = [])
formats.first
end

BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/

def formats
accept = @env['HTTP_ACCEPT']

@env["action_dispatch.request.formats"] ||=
if parameters[:format]
Array(Mime[parameters[:format]])
elsif xhr? || (accept && accept !~ BROWSER_LIKE_ACCEPTS)
elsif use_accept_header && valid_accept_header
accepts
elsif xhr?
[Mime::JS]
else
[Mime::HTML]
end
Expand Down Expand Up @@ -87,6 +92,18 @@ def negotiate_mime(order)

order.include?(Mime::ALL) ? formats.first : nil
end

protected

BROWSER_LIKE_ACCEPTS = /,\s*\*\/\*|\*\/\*\s*,/

def valid_accept_header
xhr? || (accept && accept !~ BROWSER_LIKE_ACCEPTS)
end

def use_accept_header
!self.class.ignore_accept_header
end
end
end
end
22 changes: 22 additions & 0 deletions actionpack/test/dispatch/request_test.rb
Expand Up @@ -452,6 +452,28 @@ def url_for(options = {})
assert request.formats.empty?
end

test "ignore_accept_header" do
ActionDispatch::Request.ignore_accept_header = true

begin
request = stub_request 'HTTP_ACCEPT' => 'application/xml'
request.expects(:parameters).at_least_once.returns({})
assert_equal [ Mime::HTML ], request.formats

request = stub_request 'HTTP_ACCEPT' => 'application/xml',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
request.expects(:parameters).at_least_once.returns({})
assert_equal [ Mime::JS ], request.formats

request = stub_request 'HTTP_ACCEPT' => 'application/xml',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
request.expects(:parameters).at_least_once.returns({:format => :json})
assert_equal [ Mime::JSON ], request.formats
ensure
ActionDispatch::Request.ignore_accept_header = false
end
end

test "negotiate_mime" do
request = stub_request 'HTTP_ACCEPT' => 'text/html',
'HTTP_X_REQUESTED_WITH' => "XMLHttpRequest"
Expand Down

0 comments on commit 73c94ed

Please sign in to comment.