| Module | ServerSide::HTTP::Caching |
| In: |
lib/serverside/http/caching.rb
|
| COMMA | = | ','.freeze |
Sets caching-related headers (Cache-Control and Expires).
# File lib/serverside/http/caching.rb, line 5
5: def cache(opts)
6: # check cache-control
7: remove_cache_control
8: if cache_control = opts[:cache_control]
9: add_header(CACHE_CONTROL, cache_control)
10: end
11:
12: # add an expires header
13: if expires = opts[:expires] || (opts[:ttl] && (Time.now + opts[:ttl]))
14: add_header(EXPIRES, expires.httpdate)
15: end
16: end
Matches the supplied etag against any of the entities in the If-None-Match header.
# File lib/serverside/http/caching.rb, line 49
49: def etag_match(etag)
50: return false unless @request
51: matches = @request.headers[IF_NONE_MATCH]
52: if matches
53: matches.split(COMMA).each do |e|
54: return true if e.strip == etag
55: end
56: end
57: false
58: end
Matches the supplied last modified date against the If-Modified-Since header.
# File lib/serverside/http/caching.rb, line 62
62: def modified_match(last_modified)
63: return false unless @request
64: if modified_since = @request.headers[IF_MODIFIED_SINCE]
65: last_modified.to_i == Time.parse(modified_since).to_i
66: else
67: false
68: end
69: rescue => e
70: raise BadRequestError, "Invalid value in If-Modified-Since header"
71: end
# File lib/serverside/http/caching.rb, line 82
82: def remove_cache_control
83: @headers.reject! {|h| h =~ /^#{CACHE_CONTROL}/}
84: end
Sets the Cache-Control header.
# File lib/serverside/http/caching.rb, line 74
74: def set_cache_control(directive)
75: add_header(CACHE_CONTROL, directive)
76: end
# File lib/serverside/http/caching.rb, line 78
78: def set_no_cache
79: set_cache_control(NO_CACHE)
80: end
Validates the supplied request against specified validators (etag and last-modified stamp). If a match is found, the status is changed to 304 Not Modified. Otherwise, the supplied block is invoked.
# File lib/serverside/http/caching.rb, line 21
21: def validate_cache(opts, &block)
22: valid_cache = false
23:
24: # check etag
25: if etag = opts[:etag]
26: etag = "\"#{etag}\""
27: add_header(ETAG, etag) if etag
28: valid_cache = etag_match(etag)
29: end
30:
31: # check last_modified
32: if last_modified = opts[:last_modified]
33: add_header(LAST_MODIFIED, last_modified.httpdate)
34: valid_cache ||= modified_match(last_modified)
35: end
36:
37: # set cache-related headers
38: cache(opts)
39:
40: # if not modified, we have a 304 response. Otherwise we yield to the
41: # supplied block.
42: valid_cache ? (@status = STATUS_NOT_MODIFIED) : yield(self)
43: end