ruby
15 lines · 1 tab
Alex Kumar
Jan 2026
1 tab
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
# Generate ETag from user and profile cache keys
fresh_when(etag: [user, user.profile], last_modified: user.updated_at, public: false)
# This only executes if the ETag doesn't match
render json: user
end
end
end
end
1 file · ruby
Explain with highlit
ETags enable efficient caching by allowing clients to make conditional requests that return 304 Not Modified when content hasn't changed. Rails automatically generates ETags based on response content, and fresh_when or stale? methods handle the conditional logic. When a client sends If-None-Match with a cached ETag, Rails compares it to the current response ETag and returns 304 with an empty body if they match. This saves bandwidth and server-side rendering time. ETags work particularly well for APIs serving relatively stable content like user profiles or configuration data. The challenge is ensuring ETag generation accounts for all dependencies—missing a dependency means clients receive stale data.
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
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
jwt
authentication
api
by Kai Nakamura
2 tabs
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.