mirror of
https://github.com/sinatra/sinatra
synced 2023-03-27 23:18:01 -04:00
in context
This commit is contained in:
parent
414c80a324
commit
538567319f
2 changed files with 38 additions and 3 deletions
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
Loading…
Reference in a new issue