Created
March 7, 2013 16:07
-
-
Save bcardiff/5109133 to your computer and use it in GitHub Desktop.
Rails Scoped Cache allows seamless usage of cache island that can be deleted at once. Also default expiration could be achieved by cache options. Further reference: http://quickleft.com/blog/faking-regex-based-cache-keys-in-rails
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 ScopedCache | |
attr_reader :name | |
def initialize(cache, name, options = nil) | |
@cache = cache | |
@name = name | |
@options = options | |
end | |
def read(key) | |
@cache.read(scoped_key(key)) | |
end | |
def write(key, value) | |
@cache.write(scoped_key(key), @options) | |
end | |
def fetch(key) | |
@cache.fetch(scoped_key(key), @options) do | |
yield | |
end | |
end | |
def clear | |
increment_scope_iteration | |
end | |
private | |
def scoped_key(key) | |
[name, scope_iteration, key] | |
end | |
def scope_iteration | |
@cache.fetch([name, :iteration]) do | |
1 | |
end | |
end | |
def increment_scope_iteration | |
@cache.write([name, :iteration], scope_iteration + 1) | |
end | |
end | |
module ActiveSupport | |
module Cache | |
class Store | |
def scoped(name, options = nil) | |
ScopedCache.new self, name, options | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment