From 538567319f913ca1382e52efd5130cb1c122d0a6 Mon Sep 17 00:00:00 2001 From: Blake Mizerany Date: Tue, 27 Nov 2007 23:47:48 -0800 Subject: [PATCH] in context --- lib/sinatra.rb | 30 +++++++++++++++++++++++++++--- test/application_test.rb | 11 +++++++++++ 2 files changed, 38 insertions(+), 3 deletions(-) diff --git a/lib/sinatra.rb b/lib/sinatra.rb index 2037f45..b15f0e5 100644 --- a/lib/sinatra.rb +++ b/lib/sinatra.rb @@ -32,6 +32,24 @@ module Sinatra end class EventContext + + attr_accessor :request, :response + + def initialize(request, response, route_params) + @request = request + @response = response + @route_params = route_params + @response.body = nil + end + + def params + @params ||= @route_params.merge(@request.params).symbolize_keys + end + + def method_missing(name, *args, &b) + @response.send(name, *args, &b) + end + end class Application @@ -52,9 +70,15 @@ module Sinatra end def call(env) - return [404, {}, 'Not Found'] unless event = lookup(env) - result = EventContext.new.instance_eval(&event.block) - [200, {}, result] + return [404, {}, 'Not Found'] unless result = lookup(env) + context = EventContext.new( + Rack::Request.new(env), + Rack::Response.new, + result.params + ) + returned = context.instance_eval(&result.block) + context.body ||= returned + context.finish end end diff --git a/test/application_test.rb b/test/application_test.rb index 9fe4633..9784a23 100644 --- a/test/application_test.rb +++ b/test/application_test.rb @@ -79,4 +79,15 @@ context "Calling an app" do result.body.should.equal 'foo' end + specify "gives the event access to request, response, and params" do + @app.define_event(:get, '/:foo') do + params[:foo] + params[:bar] + end + + request = Rack::MockRequest.new(@app) + result = request.get('/foo?bar=baz') + result.should.be.ok + result.body.should.equal 'foobaz' + end + end -- 2.11.4.GIT