#151 Rack Middleware
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.
- Download:
- source code Project Files in Zip (94.7 KB)
- mp4 Full Size H.264 Video (20.3 MB)
- m4v Smaller H.264 Video (13.4 MB)
- webm Full Size VP8 Video (36.2 MB)
- ogv Full Size Theora Video (28.3 MB)
Browse_code
Browse Source Code
Resources
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
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
config/environment.rb
config.middleware.use "ResponseTimer", "Load Time"
loading