This lets you have on_request
and on_response
wrappers around a builder, and optionally skip them in either case. It also gives you before and after even hooks, to do something else awesome before you proceed.
There’s a few reasons you might want to do this. One is that you may have an expensive sub stack that only needs to run on specifiec urls, or you may want to make something available only to part of the userbase. Here’s an example:
require 'meddler' use Meddler::Builder do on_request {|req| req.will_be_expensive? } use ExpensiveMiddleware use AnotherExpensiveMiddleware end
Or perhaps you want to give all of your developers Rack::Bug even in production.
require 'meddler' use Meddler::Builder do on_request do |req| req.env['warden'].authenticate user = req.env['warden'].user user && user.staff_developer? end use Rack::Bug end
In your rackup file, do this:
require 'meddler' use Meddler::Builder do on_request {|req| req.post?} before {|req| puts "yup, we passed, and now we're onto passing in the request"} use MungePostMiddleware end
Or, on response
require 'meddler' use Meddler::Builder do on_response {|resp| resp.status == 200} after {|req| puts "yup, we passed, just about to pass the response back to the middleware stack in here"} use MiddlewareThatLikesOkThings end
You can have as many on_request
and on_response
as you’d like, and processing will stop on the first one that returns false. before
and after
hooks will get called in order and be called with an instance of Rack::Request
and Rack::Response
respectively.