Skip to content

Instantly share code, notes, and snippets.

@henrik
Created April 13, 2010 13:21
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save henrik/364593 to your computer and use it in GitHub Desktop.
Ruby on Rails 2.3 cache sweeper that doesn't require a controller instance. Also an example of memcached expiration with I18n locales.
class FooSweeper < ModelOnlySweeper
observe Foo
def after_save(object)
expire_cache_for(object)
end
def after_destroy(object)
expire_cache_for(object)
end
private
def expire_cache_for(object)
base_key = Foo.some_cache_key # For example.
I18n.available_locales.each do |locale| # Can't use regexp expiration with memcached.
key = "#{base_key}:#{locale}" # Probably generated by some shared method.
expire_fragment(key)
end
end
end
class ModelOnlySweeper < ActionController::Caching::Sweeper
# We define FakeController for access to fragment_cache_key.
# Usually Rails sweepers are aware of the current controller instance. We're trying to avoid that.
# This means we have the benefit of not having to declare sweepers in controllers that update records,
# but we can only use string keys, not hashes that would be used with url_for.
module FakeController
extend ActionController::Caching::Fragments
end
private
# When you use expire_fragment(key) from a sweeper, normally method_missing will pass it
# on to the @controller. We don't have a @controller, so we define our own.
def expire_fragment(key)
if ActionController::Base.cache_configured?
full_key = FakeController.fragment_cache_key(key)
ActionController::Base.cache_store.delete(full_key)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment