Skip to content

Commit

Permalink
Fix redirect method
Browse files Browse the repository at this point in the history
	According to RFC 2616 section 14.30, for the “Location” header, “the field value consists of a single absolute URI”
	If a non absolute URI is given, the URI is reconstructed using the request.
	Tests are modified accordingly.
  • Loading branch information
giga authored and rkh committed Sep 1, 2010
1 parent 0b032a0 commit 507972e
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
8 changes: 8 additions & 0 deletions lib/sinatra/base.rb
Expand Up @@ -96,6 +96,14 @@ def block.each ; yield call ; end

# Halt processing and redirect to the URI provided.
def redirect(uri, *args)
if not uri =~ /^https?:\/\//
# According to RFC 2616 section 14.30, “the field value consists of a single absolute URI”
abs_uri = request.scheme + "://"
abs_uri << request.host
abs_uri << ":#{port}" if request.scheme == "https" and request.port != 443 or request.scheme == "http" and request.port != 80
abs_uri << uri
uri = abs_uri
end
status 302
response['Location'] = uri
halt(*args)
Expand Down
4 changes: 2 additions & 2 deletions test/filter_test.rb
Expand Up @@ -55,7 +55,7 @@ class BeforeFilterTest < Test::Unit::TestCase

get '/foo'
assert redirect?
assert_equal '/bar', response['Location']
assert_equal 'http://example.org/bar', response['Location']
assert_equal '', body
end

Expand Down Expand Up @@ -189,7 +189,7 @@ class AfterFilterTest < Test::Unit::TestCase

get '/foo'
assert redirect?
assert_equal '/bar', response['Location']
assert_equal 'http://example.org/bar', response['Location']
assert_equal '', body
end

Expand Down
6 changes: 3 additions & 3 deletions test/helpers_test.rb
Expand Up @@ -58,7 +58,7 @@ def test_default
get '/'
assert_equal 302, status
assert_equal '', body
assert_equal '/foo', response['Location']
assert_equal 'http://example.org/foo', response['Location']
end

it 'uses the code given when specified' do
Expand All @@ -72,7 +72,7 @@ def test_default
get '/'
assert_equal 301, status
assert_equal '', body
assert_equal '/foo', response['Location']
assert_equal 'http://example.org/foo', response['Location']
end

it 'redirects back to request.referer when passed back' do
Expand All @@ -85,7 +85,7 @@ def test_default
request = Rack::MockRequest.new(@app)
response = request.get('/try_redirect', 'HTTP_REFERER' => '/foo')
assert_equal 302, response.status
assert_equal '/foo', response['Location']
assert_equal 'http://example.org/foo', response['Location']
end
end

Expand Down

0 comments on commit 507972e

Please sign in to comment.