Class: ResponseBank::Middleware
- Inherits:
-
Object
- Object
- ResponseBank::Middleware
- Defined in:
- lib/response_bank/middleware.rb
Constant Summary collapse
- REQUESTED_WITH =
"HTTP_X_REQUESTED_WITH"- ACCEPT =
"HTTP_ACCEPT"- USER_AGENT =
"HTTP_USER_AGENT"
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app) ⇒ Middleware
constructor
A new instance of Middleware.
Constructor Details
#initialize(app) ⇒ Middleware
Returns a new instance of Middleware.
10 11 12 |
# File 'lib/response_bank/middleware.rb', line 10 def initialize(app) @app = app end |
Instance Method Details
#call(env) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
# File 'lib/response_bank/middleware.rb', line 14 def call(env) env['cacheable.cache'] = false gzip = env['gzip'] = env['HTTP_ACCEPT_ENCODING'].to_s.include?("gzip") status, headers, body = @app.call(env) if env['cacheable.cache'] if [200, 404, 301, 304].include?(status) headers['ETag'] = env['cacheable.key'] headers['X-Alternate-Cache-Key'] = env['cacheable.unversioned-key'] if ie_ajax_request?(env) headers["Expires"] = "-1" end end if [200, 404, 301].include?(status) && env['cacheable.miss'] # Flatten down the result so that it can be stored to memcached. if body.is_a?(String) body_string = body else body_string = +"" body.each { |part| body_string << part } end body_gz = ResponseBank.compress(body_string) # Store result cache_data = [status, headers['Content-Type'], body_gz, ] cache_data << headers['Location'] if status == 301 ResponseBank.write_to_cache(env['cacheable.key']) do payload = MessagePack.dump(cache_data) ResponseBank.write_to_backing_cache_store( env, env['cacheable.key'], payload, expires_in: env['cacheable.versioned-cache-expiry'], ) if env['cacheable.unversioned-key'] ResponseBank.write_to_backing_cache_store(env, env['cacheable.unversioned-key'], payload) end end # since we had to generate the gz version above already we may # as well serve it if the client wants it if gzip headers['Content-Encoding'] = "gzip" body = [body_gz] end end # Add X-Cache header miss = env['cacheable.miss'] x_cache = miss ? 'miss' : 'hit' x_cache += ", #{env['cacheable.store']}" unless miss headers['X-Cache'] = x_cache end [status, headers, body] end |