From fa70dc9090eab3b518d56daf3f968d07a4a05526 Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Mon, 19 Jul 2010 10:09:49 +0000 Subject: sendfile middleware: various style cleanups Favor constants over literal strings for a small garbage reduction. --- lib/rainbows/sendfile.rb | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) (limited to 'lib/rainbows/sendfile.rb') diff --git a/lib/rainbows/sendfile.rb b/lib/rainbows/sendfile.rb index 8d9b46e..c2e63be 100644 --- a/lib/rainbows/sendfile.rb +++ b/lib/rainbows/sendfile.rb @@ -1,6 +1,4 @@ # -*- encoding: binary -*- -module Rainbows - # This middleware handles X-\Sendfile headers generated by applications # or middlewares down the stack. It should be placed at the top # (outermost layer) of the middleware stack to avoid having its @@ -48,42 +46,42 @@ module Rainbows # ] # } -class Sendfile < Struct.new(:app) - - # :stopdoc: - HH = Rack::Utils::HeaderHash - # :startdoc: +class Rainbows::Sendfile < Struct.new(:app) # Body wrapper, this allows us to fall back gracefully to # +each+ in case a given concurrency model does not optimize # +to_path+ calls. class Body < Struct.new(:to_path) # :nodoc: all + CONTENT_LENGTH = 'Content-Length'.freeze def self.new(path, headers) - unless headers['Content-Length'] + unless headers[CONTENT_LENGTH] stat = File.stat(path) - headers['Content-Length'] = stat.size.to_s if stat.file? + headers[CONTENT_LENGTH] = stat.size.to_s if stat.file? end super(path) end # fallback in case our +to_path+ doesn't get handled for whatever reason def each(&block) + buf = '' File.open(to_path, 'rb') do |fp| - buf = '' yield buf while fp.read(0x4000, buf) end end end + # :stopdoc: + HH = Rack::Utils::HeaderHash + X_SENDFILE = 'X-Sendfile' + # :startdoc: + def call(env) # :nodoc: status, headers, body = app.call(env) headers = HH.new(headers) - if path = headers.delete('X-Sendfile') + if path = headers.delete(X_SENDFILE) body = Body.new(path, headers) unless body.respond_to?(:to_path) end [ status, headers, body ] end end - -end -- cgit v1.2.3-24-ge0c7