module MyApp
class Application < Rails::Application
config.load_defaults 6.1
# Enable response compression
config.middleware.use Rack::Deflater
end
end
Large JSON payloads consume bandwidth and increase latency, especially for mobile clients on slow connections. Rack::Deflater middleware automatically compresses responses using gzip when clients send Accept-Encoding: gzip headers. This typically reduces payload sizes by 70-90% for JSON, dramatically improving transfer times. The middleware is smart enough to skip compression for small responses where overhead exceeds benefit, and it respects already-compressed content types like images. The CPU cost of compression is negligible compared to network transfer time savings. I configure deflater early in the middleware stack so it wraps the entire response, and I verify compression with browser dev tools or curl with verbose output.
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
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
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
Share this code
Here's the card — post it anywhere.