lib/roda/plugins/middleware.rb in roda-3.54.0 vs lib/roda/plugins/middleware.rb in roda-3.55.0
- old
+ new
@@ -71,15 +71,20 @@
# roda middleware in the same application.
# :handle_result :: Callable object that will be called with request environment
# and rack response for all requests passing through the middleware,
# after either the middleware or next app handles the request
# and returns a response.
+ # :forward_response_headers :: Whether changes to the response headers made inside
+ # the middleware's route block should be applied to the
+ # final response when the request is forwarded to the app.
+ # Defaults to false.
def self.configure(app, opts={}, &block)
app.opts[:middleware_env_var] = opts[:env_var] if opts.has_key?(:env_var)
app.opts[:middleware_env_var] ||= 'roda.forward_next'
app.opts[:middleware_configure] = block if block
app.opts[:middleware_handle_result] = opts[:handle_result]
+ app.opts[:middleware_forward_response_headers] = opts[:forward_response_headers]
end
# Forwarder instances are what is actually used as middleware.
class Forwarder
# Make a subclass of +mid+ to use as the current middleware,
@@ -106,10 +111,14 @@
false
end
if call_next
res = @app.call(env)
+
+ if modified_headers = env.delete('roda.response_headers')
+ res[1] = modified_headers.merge(res[1])
+ end
end
if handle_result = @mid.opts[:middleware_handle_result]
handle_result.call(env, res)
end
@@ -133,19 +142,25 @@
# Override the route block so that if no route matches, we throw so
# that the next middleware is called. Old Dispatch API.
def call(&block)
super do |r|
res = instance_exec(r, &block) # call Fallback
- throw :next, true if r.forward_next
+ if r.forward_next
+ r.env['roda.response_headers'] = response.headers if opts[:middleware_forward_response_headers]
+ throw :next, true
+ end
res
end
end
# Override the route block so that if no route matches, we throw so
# that the next middleware is called.
def _roda_run_main_route(r)
res = super
- throw :next, true if r.forward_next
+ if r.forward_next
+ r.env['roda.response_headers'] = response.headers if opts[:middleware_forward_response_headers]
+ throw :next, true
+ end
res
end
end
module RequestMethods