Code Explainers

Ruby on Rails code explainers

ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"
 

Live-updating comments with Turbo in Rails

turbo-streams callbacks associations
Intermediate 8 steps
ruby
class ReportBatcher
  BATCH_SIZE = 500
 
  def initialize(account)

Batching monthly email summaries in Rails

batching service-object background-jobs
Intermediate 7 steps
ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true, counter_cache: true
  belongs_to :author, class_name: "User"
 

How polymorphic comments work in Rails

polymorphic-association concerns counter-cache
Intermediate 8 steps
ruby
class SessionsController < ApplicationController
  MAX_ATTEMPTS = 5
  THROTTLE_WINDOW = 15.minutes
 

Throttling failed logins in Rails

rate-limiting authentication caching
Intermediate 7 steps
ruby
class ProductsController < ApplicationController
  def index
    @products = Product
      .includes(:category, :brand)

Building a safe filterable product index in Rails

query objects scopes strong parameters
Intermediate 8 steps
ruby
class HostnameValidator < ActiveModel::EachValidator
  MAX_LENGTH = 253
  LABEL = /\A(?!-)[a-z0-9-]{1,63}(?<!-)\z/i
 

Writing a custom hostname validator in Rails

validation custom validator regex
Intermediate 8 steps
ruby
class PaymentsController < ApplicationController
  before_action :require_idempotency_key
 
  def create

Idempotent payment creation in Rails

idempotency transactions race-conditions
Advanced 10 steps
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  has_many :respondents, dependent: :nullify
 

Nested survey forms in Rails

nested-attributes validations associations
Intermediate 9 steps
ruby
class OrderConfirmationJob < ApplicationJob
  queue_as :mailers
 
  retry_on Net::OpenTimeout, wait: :polynomially_longer, attempts: 5

Resilient background jobs in Rails

background-jobs retries idempotency
Intermediate 8 steps
ruby
module SoftDeletable
  extend ActiveSupport::Concern
 
  included do

How a soft-delete concern works in Rails

concerns soft-delete scopes
Intermediate 8 steps
ruby
class Post < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true

How a Rails model builds unique slugs

slugs callbacks validations
Intermediate 7 steps
ruby
class Article < ApplicationRecord
  before_validation :generate_slug, on: :create
 
  validates :slug, presence: true, uniqueness: true,

How URL slugs work in Rails

callbacks validations slugs
Intermediate 7 steps
ruby
class CheckoutService
  Result = Struct.new(:success?, :order, :error, keyword_init: true)
 
  def self.call(...)

How a Rails checkout service object works

service object transactions result object
Intermediate 9 steps
ruby
class User < ApplicationRecord
  has_one_attached :avatar
 
  validate :acceptable_avatar

Validating and serving avatars with Active Storage in Rails

active storage file uploads validation
Intermediate 9 steps
ruby
class Article < ApplicationRecord
  belongs_to :author
 
  default_scope { where(deleted_at: nil) }

How scopes compose in Rails

scopes query-composition activerecord
Intermediate 9 steps
ruby
class Employee < ApplicationRecord
  validates :name, presence: true
  validates :salary, numericality: { greater_than: 0 }
 

How STI models share behavior in Rails

single-table-inheritance inheritance method-overriding
Intermediate 8 steps
ruby
class ArticlesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_article, only: %i[show edit update destroy]
  before_action :authorize_owner!, only: %i[edit update destroy]

How before_action filters guard a Rails controller

filters authorization callbacks
Intermediate 9 steps
ruby
class CreateCommentsWithCounterCache < ActiveRecord::Migration[7.1]
  def change
    create_table :posts do |t|
      t.string :title, null: false

How counter caches work in Rails

counter-cache migrations associations
Intermediate 6 steps