Rack middleware is a way to filter a request and response coming into your application. In this episode I show how to modify the response body using middleware.
Special thanks to Josh Peek for answering some questions I had on this topic.
Update: making the code below thread safe by duplicating self on call.
Note: as wldock and remi pointed out in the comments, it is important to change the headers["Content-Length"] value to reflect the new body length. See their comments for details.
bash
rake middleware
rake middleware
lib/response_timer.rb
class ResponseTimer
def initialize(app, message = "Response Time")
@app = app
@message = message
end
def call(env)
dup._call(env)
end
def _call(env)
@start = Time.now
@status, @headers, @response = @app.call(env)
@stop = Time.now
[@status, @headers, self]
end
def each(&block)
block.call("<!-- #{@message}: #{@stop - @start} -->\n") if @headers["Content-Type"].include? "text/html"
@response.each(&block)
end
end