Skip to content

Instantly share code, notes, and snippets.

@hitrecord
Last active December 16, 2015 01:59
Show Gist options
  • Save hitrecord/5358660 to your computer and use it in GitHub Desktop.
Save hitrecord/5358660 to your computer and use it in GitHub Desktop.
# Redis::Objects is the only requirement for this solution
require 'redis/objects'
module Redis::CacheKeys
class ReservedKey < Exception; end
def self.included(base)
base.class_eval do
include Redis::Objects unless base.included_modules.include?(Redis::Objects)
set "cache_keys"
end
end
def cache_compound_key(key)
raise ReservedKey, "#{key} is a reserved key." if key == 'cache_keys'
"#{self.class.table_name}_#{self.id}_#{key}"
end
def cache_key(key)
cache_compound_key(key).tap do |compound_key|
self.cache_keys << compound_key
end
end
def cache_expire(key = nil)
# When key is nil, expire all cache keys
if key.nil?
self.cache_keys.each do |compound_key|
ActionController::Base.new.expire_fragment(compound_key)
end
else
cache_compound_key(key).tap do |compound_key|
ActionController::Base.new.expire_fragment(compound_key)
end
end
end
end
@hitrecord
Copy link
Author

Usage:

some_model = Model.find(123456)

Slow view to cache

cache(some_model.cache_key('slow_area')) do

...

Later, we want to only expire this 'slow_area'

some_model.cache_expire('slow_area')

Even later, we want to expire everything for this model

some_model.cache_expire

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment