Created
September 16, 2013 21:41
-
-
Save arthurnn/6586975 to your computer and use it in GitHub Desktop.
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
module IdentityCache | |
BACKEND_KEY = 'idc:backend:key' | |
def with_memoization(&block) | |
Thread.current[IdentityCache::BACKEND_KEY] = MemoizedDecorator.new(IdentityCache.cache_backend) | |
yield | |
ensure | |
Thread.current[IdentityCache::BACKEND_KEY] = nil | |
end | |
def fetch(key, &block) | |
if (entry = CacheEntry.find(key)).nil? | |
entry.value = yield | |
entry.save | |
end | |
entry.value | |
end | |
def delete(key) | |
CacheEntry.delete(key) | |
end | |
class CacheEntry | |
DELETED = 'D' | |
def initialize(key, value, cas) | |
@key, @value. @cas = key, value, cas | |
end | |
def nil? | |
@value.nil? || @value == DELETED | |
end | |
def value | |
@value == IdentityCache::CACHED_NIL ? nil : @value | |
end | |
def value=(v) | |
@value = v.nil? ? IdentityCache::CACHED_NIL : v | |
end | |
def save | |
if @cas.nil? | |
backend.add(@key, @value) | |
else | |
backend.cas(@key, @value, @cas) | |
end | |
end | |
def self.find(key) | |
value, cas = backend.get(key) | |
CacheEntry.new(key, value, cas) | |
end | |
def self.delete(key) | |
backend.replace(key, DELETED, ttl: 1) | |
end | |
def self.backend | |
Thread.current[IdentityCache::BACKEND_KEY] || IdentityCache.cache_backend | |
end | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment