ruby 63 lines · 4 tabs

Hot Path Memoization (within request only)

Shared by codesnips Jan 2026
4 tabs
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
4 files · ruby Explain with highlit

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

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
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

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
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

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<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)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Hot Path Memoization (within request only) — share card
Link copied