Using :halt to set body

This commit is contained in:
Blake Mizerany 2007-11-28 13:25:14 -08:00
parent d9cad760a2
commit de6f9818b9
3 changed files with 43 additions and 9 deletions

View File

@ -67,7 +67,7 @@ module Sinatra
attr_accessor :request, :response attr_accessor :request, :response
dslify_writter :status, :body dslify_writter :status
def initialize(request, response, route_params) def initialize(request, response, route_params)
@request = request @request = request
@ -80,11 +80,28 @@ module Sinatra
@params ||= @route_params.merge(@request.params).symbolize_keys @params ||= @route_params.merge(@request.params).symbolize_keys
end end
def body(content)
throw :halt, content
end
def complete(returned) def complete(returned)
@response.body ||= returned _render(@response.body || returned)
end
protected
def _body=(content)
@response.body = content
end
def _render(content)
# This is for renderers to override
# See http://sinatrarb.com/renderers
content
end end
def method_missing(name, *args, &b) def method_missing(name, *args, &b)
raise NoMethodError.new('body=') if name == :body=
@response.send(name, *args, &b) @response.send(name, *args, &b)
end end
@ -98,7 +115,7 @@ module Sinatra
def to_result(cx, *args) def to_result(cx, *args)
cx.status(302) cx.status(302)
cx.header.merge!('Location' => @path) cx.header.merge!('Location' => @path)
cx.body('') cx.send :_body=, ''
end end
end end
@ -130,7 +147,7 @@ module Sinatra
[:complete, context.instance_eval(&result.block)] [:complete, context.instance_eval(&result.block)]
end end
result = returned.to_result(context) result = returned.to_result(context)
context.body = String === result ? [*result] : result context.send :_body=, String === result ? [*result] : result
context.finish context.finish
end end
@ -241,7 +258,7 @@ end
class String class String
def to_result(cx, *args) def to_result(cx, *args)
cx.body self cx.send :_body=, self
end end
end end

View File

@ -35,4 +35,21 @@ context "Sinatra" do
body.should.equal 'Mizerany' body.should.equal 'Mizerany'
end end
specify "body sets content and ends event" do
Sinatra::EventContext.any_instance.expects(:foo).never
get '/set_body' do
body 'Hello!'
body 'Not this'
foo
end
get_it '/set_body'
should.be.ok
body.should.equal 'Hello!'
end
end end

View File

@ -83,7 +83,7 @@ context "An app returns" do
specify "the body set if set before the last" do specify "the body set if set before the last" do
@app.define_event(:get, '/') do @app.define_event(:get, '/') do
self.body = 'Blake' body 'Blake'
'Mizerany' 'Mizerany'
end end