Last active
August 29, 2015 14:09
-
-
Save joker1007/7041e687efe342a826af to your computer and use it in GitHub Desktop.
Rackミドルウェアとして動作する1リクエスト毎に勝手に消える超簡易キャッシュストア
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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