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
class Order class InvalidTransition < StandardError; end TRANSITIONS = {
A state machine for order transitions in Ruby
state-machine
data-driven
error-handling
Intermediate
8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
ruby
require "csv" def parse_transaction_row(line) fields = CSV.parse_line(line, headers: false, skip_blanks: true)
Parsing one CSV transaction row in Ruby
parsing
type-coercion
error-handling
Intermediate
6 steps
php
<?php namespace App\Cache;
A content-hashed fragment cache in PHP
caching
content-hashing
atomic-writes
Intermediate
10 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.