Skip to content

Instantly share code, notes, and snippets.

@betamatt
Created April 20, 2010 14:41
Show Gist options
  • Save betamatt/372542 to your computer and use it in GitHub Desktop.
Save betamatt/372542 to your computer and use it in GitHub Desktop.
Handle cache inconsistency by clearing affected models. Allow use of counter caches.
# include Cash::Extensions after you declare is_cached for a class
module Cash
module Extensions
def self.included(base)
base.send(:extend, ClassMethods)
base.send(:include, InstanceMethods)
end
module ClassMethods
# Counter caches aren't needed with cache-money since you can cache the actual count queries but
# use this hack if you want to use counter caches anyway.
def update_counters_with_cache_expire(id, counters)
update_counters_without_cache_expire(id, counters)
find(id).expire_caches
end
def self.extended(base)
class << base
alias_method_chain :update_counters, :cache_expire
end
end
end
module InstanceMethods
def save_with_cache_expire(*args)
save_without_cache_expire(*args)
rescue ActiveRecord::StaleObjectError => e
expire_caches
raise e
end
def save_with_cache_expire!(*args)
save_without_cache_expire!(*args)
rescue ActiveRecord::StaleObjectError => e
expire_caches
raise e
end
def self.included(base)
base.alias_method_chain :save, :cache_expire
base.alias_method_chain :save!, :cache_expire
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment