document and further spec out ResponseHelpers

This commit is contained in:
Ryan Tomayko 2008-04-13 05:17:39 -04:00
parent ca9ac7b5ae
commit d343d27d87
2 changed files with 56 additions and 5 deletions

View File

@ -376,15 +376,40 @@ module Sinatra
header('Cache-Control' => 'private') if headers['Cache-Control'] == 'no-cache'
end
end
# Helper methods for building various aspects of the HTTP response.
module ResponseHelpers
# Immediately halt response execution by redirecting to the resource
# specified. The +path+ argument may be an absolute URL or a path
# relative to the site root. Additional arguments are passed to the
# halt.
#
# With no integer status code, a '302 Temporary Redirect' response is
# sent. To send a permanent redirect, pass an explicit status code of
# 301:
#
# redirect '/somewhere/else', 301
#
# NOTE: No attempt is made to rewrite the path based on application
# context. The 'Location' response header is set verbatim to the value
# provided.
def redirect(path, *args)
status(302)
headers 'Location' => path
header 'Location' => path
throw :halt, *args
end
# Access or modify response headers. With no argument, return the
# underlying headers Hash. With a Hash argument, add or overwrite
# existing response headers with the values provided:
#
# headers 'Content-Type' => "text/html; charset=utf-8",
# 'Last-Modified' => Time.now.httpdate,
# 'X-UA-Compatible' => 'IE=edge'
#
# This method also available in singular form (#header).
def headers(header = nil)
@response.headers.merge!(header) if header
@response.headers

View File

@ -26,7 +26,22 @@ context "Sinatra" do
should.be.ok
body.should.equal 'Hello Blake'
end
specify "gives access to underlying response header Hash" do
get '/' do
header['X-Test'] = 'Is this thing on?'
headers 'X-Test2' => 'Foo', 'X-Test3' => 'Bar'
''
end
get_it '/'
should.be.ok
headers.should.include 'X-Test'
headers['X-Test'].should.equal 'Is this thing on?'
headers.should.include 'X-Test3'
headers['X-Test3'].should.equal 'Bar'
end
specify "follows redirects" do
get '/' do
redirect '/blake'
@ -55,7 +70,18 @@ context "Sinatra" do
headers['Location'].should.equal 'foo'
body.should.equal 'blah'
end
specify "redirects permanently with 301 status code" do
get "/" do
redirect 'foo', 301
end
get_it '/'
should.be.redirection
headers['Location'].should.equal 'foo'
status.should.equal 301
body.should.be.empty
end
specify "body sets content and ends event" do
Sinatra::EventContext.any_instance.expects(:foo).never