Skip to content
This repository
Fetching contributors…

Cannot retrieve contributors at this time

file 32 lines (27 sloc) 0.623 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
require 'digest/md5'

module Rack
  # Automatically sets the ETag header on all String bodies
  class ETag
    def initialize(app)
      @app = app
    end

    def call(env)
      status, headers, body = @app.call(env)

      if !headers.has_key?('ETag')
        digest, body = digest_body(body)
        headers['ETag'] = %("#{digest}")
      end

      [status, headers, body]
    end

    private
      def digest_body(body)
        digest = Digest::MD5.new
        parts = []
        body.each do |part|
          digest << part
          parts << part
        end
        [digest.hexdigest, parts]
      end
  end
end
Something went wrong with that request. Please try again.