ruby
20 lines · 4 steps
Russian doll caching that busts itself in Rails
How touch: true and composite cache keys keep fragment caches fresh without manual expiry.
Explained by
highlit
1module ProductsHelper
2 def cached_product_row(product)
3 cache [product, current_user.role] do
4 render partial: "products/row", locals: { product: product }
5 end
6 end
7end
8
9class Product < ApplicationRecord
10 belongs_to :category, touch: true
11 has_many :reviews, dependent: :destroy
12
13 def cache_key_with_reviews
14 "#{cache_key_with_version}/reviews-#{reviews.maximum(:updated_at).to_i}"
15 end
16end
17
18class Review < ApplicationRecord
19 belongs_to :product, touch: true
20end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Composite cache keys let you vary a fragment by both the record and the viewer without writing expiry code.
- 2touch: true propagates updated_at up the association chain so parent caches invalidate when children change.
- 3Baking a child's max updated_at into a parent's cache key expires the parent whenever any child is modified.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/russian-doll-caching-that-busts-itself-in-rails-explained-ruby-c537/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.