From de6f9818b9aef18eb8e69f8320c6482a4824c586 Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Wed, 28 Nov 2007 13:25:14 -0800 Subject: [PATCH] Using :halt to set body --- lib/sinatra.rb | 33 +++++++++++++++++++++++++-------- test/app_test.rb | 17 +++++++++++++++++ test/application_test.rb | 2 +- 3 files changed, 43 insertions(+), 9 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index f1aae73..604324c 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -67,7 +67,7 @@ module Sinatra attr_accessor :request, :response - dslify_writter :status, :body + dslify_writter :status def initialize(request, response, route_params) @request = request @@ -80,14 +80,31 @@ module Sinatra @params ||= @route_params.merge(@request.params).symbolize_keys end - def complete(returned) - @response.body ||= returned + def body(content) + throw :halt, content end - def method_missing(name, *args, &b) - @response.send(name, *args, &b) + def complete(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 + + def method_missing(name, *args, &b) + raise NoMethodError.new('body=') if name == :body= + @response.send(name, *args, &b) + end + end class NotFound @@ -98,7 +115,7 @@ module Sinatra def to_result(cx, *args) cx.status(302) cx.header.merge!('Location' => @path) - cx.body('') + cx.send :_body=, '' end end @@ -130,7 +147,7 @@ module Sinatra [:complete, context.instance_eval(&result.block)] end result = returned.to_result(context) - context.body = String === result ? [*result] : result + context.send :_body=, String === result ? [*result] : result context.finish end @@ -241,7 +258,7 @@ end class String def to_result(cx, *args) - cx.body self + cx.send :_body=, self end end diff --git a/test/app_test.rb b/test/app_test.rb index 6586203..8eb1ee8 100644 --- a/test/app_test.rb +++ b/test/app_test.rb @@ -35,4 +35,21 @@ context "Sinatra" do body.should.equal 'Mizerany' 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 diff --git a/test/application_test.rb b/test/application_test.rb index 3216f5d..a6dd460 100644 --- a/test/application_test.rb +++ b/test/application_test.rb @@ -83,7 +83,7 @@ context "An app returns" do specify "the body set if set before the last" do @app.define_event(:get, '/') do - self.body = 'Blake' + body 'Blake' 'Mizerany' end -- 2.11.4.GIT