Skip to content

Instantly share code, notes, and snippets.

@debprado
Forked from henrik/foo_sweeper.rb
Created May 10, 2010 19:48
Show Gist options
  • Save debprado/396444 to your computer and use it in GitHub Desktop.
Save debprado/396444 to your computer and use it in GitHub Desktop.
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