class CacheNamespace
attr_reader :name
def initialize(name, store: Rails.cache)
@name = name.to_s
@store = store
end
def version
@store.fetch(version_key, expires_in: nil) { 1 }
end
def key_for(*parts)
digest = Digest::SHA1.hexdigest(parts.flatten.join("/"))
[name, "v#{version}", digest].join(":")
end
def bump!
next_version = @store.increment(version_key)
return next_version if next_version
# Key was absent (or not integer-backed): seed it explicitly.
@store.write(version_key, 2)
2
end
private
def version_key
"cache-namespace:#{name}:version"
end
end
module Cacheable
extend ActiveSupport::Concern
class_methods do
def namespaced_cache(scope = nil)
parts = [model_name.cache_key, scope].compact
CacheNamespace.new(parts.join(":"))
end
end
def cache_namespace
self.class.namespaced_cache(id)
end
def cached_fetch(*parts, expires_in: 1.hour, &block)
key = cache_namespace.key_for(*parts)
Rails.cache.fetch(key, expires_in: expires_in, &block)
end
def invalidate_cache!
cache_namespace.bump!
end
end
class ProductsController < ApplicationController
before_action :set_product, only: %i[show update]
def show
payload = @product.cached_fetch(:show, request.format.symbol) do
ProductSerializer.new(@product).as_json
end
render json: payload
end
def update
if @product.update(product_params)
@product.invalidate_cache!
render json: @product
else
render json: { errors: @product.errors }, status: :unprocessable_entity
end
end
private
def set_product
@product = Product.find(params[:id])
end
def product_params
params.require(:product).permit(:name, :price, :description)
end
end
This snippet shows a lightweight way to invalidate large groups of Rails cache entries at once without enumerating or deleting individual keys. The idea is a single indirection: every cache key for a domain is prefixed with a per-namespace version counter stored in the cache store itself. Bumping that counter changes every derived key, so old entries become unreachable and expire naturally under LRU. This is far cheaper than pattern-based deletes, which most stores (including Memcached and Redis at scale) cannot do efficiently.
In CacheNamespace, the class wraps a logical group such as "products" or a tenant scope. #version reads the counter from Rails.cache, seeding it to 1 via fetch when absent so the namespace is always valid on first use. #key_for composes the final cache key from the namespace name, the current version, and the caller-supplied parts, joined with Digest so long or user-derived fragments stay bounded in length. The crucial method is #bump!, which uses the store's atomic increment so concurrent writers never lose an update; when increment returns nil (key not yet present) it falls back to writing an initial value.
In Cacheable concern, the pattern is exposed to models with namespaced_cache, giving each record a stable namespace derived from its class and a scope. cached_fetch delegates to Rails.cache.fetch through the namespace's key_for, and invalidate_cache! simply calls bump!. Because the version lives in the key, invalidation is O(1) regardless of how many entries exist.
In ProductsController, show reads through cached_fetch so repeat requests skip the database, while update calls invalidate_cache! inside the success branch so a single write instantly retires every cached view of that record. The trade-off is that stale keys are not actively purged — they linger until evicted — so this suits high-read, bounded-key workloads rather than unbounded key spaces. A subtle pitfall is forgetting that the version key must itself survive eviction; keeping it small and hot generally keeps it resident. When a whole class of caches must drop together (deploys, schema changes, bulk imports), bumping one shared namespace beats tracking thousands of individual keys.
Related snips
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
class Post < ApplicationRecord
belongs_to :author, class_name: 'User'
has_many :comments, dependent: :destroy
scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
scope :draft, -> { where(published_at: nil) }
ActiveRecord scopes for reusable query logic
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
class PostsController < ApplicationController
def index
@posts = Post.includes(:author)
.order(created_at: :desc)
.page(params[:page])
.per(10)
Turbo Frames: infinite scroll with lazy-loading frame
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<form data-controller="query-sync" data-action="change->query-sync#apply">
<select name="status" class="rounded border p-2">
<option value="">Any</option>
<option value="open">Open</option>
<option value="closed">Closed</option>
</select>
Filter UI that syncs query params via Stimulus (no front-end router)
Share this code
Here's the card — post it anywhere.