Skip to content

Instantly share code, notes, and snippets.

@joker1007
Last active August 29, 2015 14:09
Show Gist options
  • Save joker1007/7041e687efe342a826af to your computer and use it in GitHub Desktop.
Save joker1007/7041e687efe342a826af to your computer and use it in GitHub Desktop.
Rackミドルウェアとして動作する1リクエスト毎に勝手に消える超簡易キャッシュストア
class CacheByRequest
def self.read(key)
if Thread.current[:cache_by_request]
Thread.current[:cache_by_request].read(key)
else
raise "before CacheByRequest::Store initialization"
end
end
def self.write(key, val)
if Thread.current[:cache_by_request]
Thread.current[:cache_by_request].write(key, val)
else
raise "before CacheByRequest::Store initialization"
end
end
def self.with_stubbed
Thread.current[:cache_by_request] = Store.new
yield
ensure
Thread.current[:cache_by_request] = nil
end
def initialize(app)
@app = app
end
def call(env)
Thread.current[:cache_by_request] = Store.new
@app.call(env)
ensure
Thread.current[:cache_by_request] = nil
end
class Store
def initialize
@data = HashWithIndifferentAccess.new
end
def read(key)
@data[key]
end
def write(key, val)
@data[key] = val
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment