diff --git a/lib/sinatra/base.rb b/lib/sinatra/base.rb index 490ebc70fb..56150f30c7 100644 --- a/lib/sinatra/base.rb +++ b/lib/sinatra/base.rb @@ -100,6 +100,12 @@ def not_found(body=nil) error 404, body end + # Set multiple response headers with Hash. + def headers(hash=nil) + response.headers.merge! hash if hash + response.headers + end + # Access the underlying Rack session. def session env['rack.session'] ||= {} @@ -379,7 +385,7 @@ def forward status, headers, body = @app.call(@request.env) @response.status = status @response.body = body - headers.each { |k, v| @response[k] = v } + @response.headers.merge! headers nil end diff --git a/lib/sinatra/compat.rb b/lib/sinatra/compat.rb index 1c13901911..6961996a44 100644 --- a/lib/sinatra/compat.rb +++ b/lib/sinatra/compat.rb @@ -87,12 +87,10 @@ def self.const_missing(const_name) #:nodoc: end # Deprecated. Use: response['Header-Name'] - def headers(header=nil) - sinatra_warn "The 'headers' method is deprecated; use 'response' instead." - response.headers.merge!(header) if header - response.headers + def header(header=nil) + sinatra_warn "The 'header' method is deprecated; use 'headers' instead." + headers(header) end - alias :header :headers # Deprecated. Use: halt def stop(*args, &block) diff --git a/test/helpers_test.rb b/test/helpers_test.rb index ef381624e8..f9aea2d62c 100644 --- a/test/helpers_test.rb +++ b/test/helpers_test.rb @@ -140,6 +140,36 @@ end end +describe 'Helpers#headers' do + it 'sets headers on the response object when given a Hash' do + mock_app { + get '/' do + headers 'X-Foo' => 'bar', 'X-Baz' => 'bling' + 'kthx' + end + } + + get '/' + assert ok? + assert_equal 'bar', response['X-Foo'] + assert_equal 'bling', response['X-Baz'] + assert_equal 'kthx', body + end + + it 'returns the response headers hash when no hash provided' do + mock_app { + get '/' do + headers['X-Foo'] = 'bar' + 'kthx' + end + } + + get '/' + assert ok? + assert_equal 'bar', response['X-Foo'] + end +end + describe 'Helpers#session' do it 'uses the existing rack.session' do mock_app {