Skip to content

Instantly share code, notes, and snippets.

@bcardiff
Created March 7, 2013 16:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bcardiff/5109133 to your computer and use it in GitHub Desktop.
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
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