class StupidCache

Constants

VERSION

Public Class Methods

new(app, opts) click to toggle source
   # File lib/stupid_cache.rb
 8 def initialize(app, opts)
 9   @app = app
10   @cache = opts[:cache]
11   @expiry = opts[:expiry] || 60
12   @limit = opts[:limit] || 250 # memcached limit
13 end

Public Instance Methods

call(env) click to toggle source
   # File lib/stupid_cache.rb
15 def call(env)
16   return @app.call(env) unless env["REQUEST_METHOD"] == "GET"
17   key = Rack::Request.new(env).url
18 
19   # Don't allow keys to get too long.
20   return @app.call(env) if key.size > @limit
21 
22   # return value
23   begin
24     response = @cache.get(key)
25     unless response
26       response = @app.call(env)
27 
28       # ensure any memcache failures are non-fatal
29       begin
30         @cache.set(key, response, @expiry)
31       rescue => err
32         env['rack.errors'].write("#{self.class} error: #{err.inspect}\n")
33       end
34     end
35     response
36   rescue => err
37     env['rack.errors'].write("#{self.class} error: #{err.inspect}\n")
38     @app.call(env)
39   end
40 end