class CacheNamespace
def initialize(name)
@name = name
end
def version
Rails.cache.fetch("cache_ns:#{@name}", expires_in: 1.year) { SecureRandom.hex(6) }
end
def bump!
Rails.cache.write("cache_ns:#{@name}", SecureRandom.hex(6), expires_in: 1.year)
end
end
ns = CacheNamespace.new('trending_snips')
Rails.cache.fetch("trending:#{ns.version}", expires_in: 10.minutes) { Snip.trending.limit(20).to_a }
When cache structures change, you want to invalidate safely without flushing the world. Use a namespace version key (per feature) and incorporate it into cache keys.