module RequestStore
def self.store
Thread.current[:request_store] ||= {}
end
def self.fetch(key)
return store[key] if store.key?(key)
store[key] = yield
end
def self.clear!
Thread.current[:request_store] = {}
end
end
class RequestStoreMiddleware
def initialize(app)
@app = app
end
def call(env)
RequestStore.clear!
@app.call(env)
ensure
RequestStore.clear!
end
end
# config/application.rb
# config.middleware.insert_after ActionDispatch::Executor, RequestStoreMiddleware
module Memoizable
extend ActiveSupport::Concern
private
def request_memoize(method_name, *args)
key = memo_key(method_name, args)
RequestStore.fetch(key) { yield }
end
def memo_key(method_name, args)
scope = self.class.name
"#{scope}##{method_name}:#{args.map(&:to_s).join(',')}"
end
end
class FeatureFlags
include Memoizable
def initialize(account)
@account = account
end
def enabled?(name)
flags_for(@account.id).include?(name.to_s)
end
def flags_for(account_id)
request_memoize(:flags_for, account_id) do
Flag.where(account_id: account_id, enabled: true)
.pluck(:name)
.to_set
end
end
end
This snippet shows how to memoize expensive lookups only for the duration of a single request — a middle ground between recomputing on every call and caching across requests (which risks stale data and cross-tenant leakage). The pattern is common in Rails apps where a value like the current tenant's feature flags or a permission set is read dozens of times per request but must never survive past it.
In RequestStore, a thread-local Hash is exposed through RequestStore.store. Using Thread.current scopes the state to the thread handling the request, so under threaded servers like Puma two concurrent requests never see each other's data. The key detail is clear!, which must run at the end of every request; otherwise a thread pulled from the pool would carry stale values into the next request — the classic bug that makes request-scoped caches leak.
In RequestStoreMiddleware, that lifetime guarantee is enforced. The ensure block calls RequestStore.clear! no matter how the downstream stack returns or raises, which is exactly why it belongs in middleware rather than a controller after_action: middleware always wraps the full request, including error paths.
In Memoizable concern, request_memoize builds a stable cache key from the method name and its arguments and delegates storage to RequestStore. The fetch(key) { ... } idiom computes the block only on a miss. Note false and nil are handled correctly because key? is checked rather than truthiness — a subtle pitfall with ||=-style memoization, where a legitimately falsey result gets recomputed every call.
In FeatureFlags, the concern is applied to a genuinely expensive method, flags_for, that hits the database. Called repeatedly in views and policies, it now runs its query once per request. The trade-off is deliberate: values are always fresh at the start of each request, so there is no invalidation logic to maintain, but nothing is shared between requests. This approach fits read-heavy, per-request-stable data; it is the wrong tool for data that should persist across requests or be shared between users.
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.