class Rack::ConditionalGet

Middleware that enables conditional GET using If-None-Match and If-Modified-Since. The application should set either or both of the Last-Modified or Etag response headers according to RFC 2616. When either of the conditions is met, the response body is set to be zero length and the response status is set to 304 Not Modified.

Applications that defer response body generation until the body’s each message is received will avoid response body generation completely when a conditional GET matches.

Adapted from Michael Klishin’s Merb implementation: github.com/wycats/merb/blob/master/merb-core/lib/merb-core/rack/middleware/conditional_get.rb

Constants

ETAG_KEY
LAST_MODIFIED_KEY
MODIFIED_SINCE_KEY
NONE_MATCH_KEY
VERB_KEY
VERSION

Public Class Methods

new(app) click to toggle source
# File lib/rack/conditional_get.rb, line 22
def initialize(app)
  @app = app
end

Public Instance Methods

call(env) click to toggle source
# File lib/rack/conditional_get.rb, line 26
def call(env)
  @env = env
  @status, @headers, @body = @app.call(@env)
  if (get? || head?) && (@status == 200 && fresh?)
    @status = 304
    headers.delete("Content-Type")
    headers.delete("Content-Length")
    body = Rack::BodyProxy.new([]) do
      @body.close if @body.respond_to?(:close)
    end
    [@status, @headers, body]
  else
    @app.call(@env)
  end
end

Private Instance Methods

etag() click to toggle source
# File lib/rack/conditional_get.rb, line 54
        def etag
  headers[ETAG_KEY]
end
etag_matches?() click to toggle source
# File lib/rack/conditional_get.rb, line 58
        def etag_matches?
  etag && none_match && etag == none_match
end
fresh?() click to toggle source
# File lib/rack/conditional_get.rb, line 42
        def fresh?
  modified_since || etag_matches?
end
get?() click to toggle source
# File lib/rack/conditional_get.rb, line 74
        def get?
  verb == "GET"
end
head?() click to toggle source
# File lib/rack/conditional_get.rb, line 78
        def head?
  verb == "HEAD"
end
headers() click to toggle source
# File lib/rack/conditional_get.rb, line 46
        def headers
  @headers
end
last_modified() click to toggle source
# File lib/rack/conditional_get.rb, line 66
        def last_modified
  headers[LAST_MODIFIED_KEY]
end
modified_since() click to toggle source
# File lib/rack/conditional_get.rb, line 62
        def modified_since
  @env[MODIFIED_SINCE_KEY]
end
modified_since?() click to toggle source
# File lib/rack/conditional_get.rb, line 70
        def modified_since?
  last_modified && modified_since && modified_since >= last_modified
end
none_match() click to toggle source
# File lib/rack/conditional_get.rb, line 50
        def none_match
  @env[NONE_MATCH_KEY]
end
verb() click to toggle source
# File lib/rack/conditional_get.rb, line 82
        def verb
  @env[VERB_KEY]
end