Code Explainers

Ruby on Rails code explainers

ruby
class DashboardMetrics
  CACHE_TTL = 15.minutes
 
  def initialize(account)

Caching dashboard metrics in Rails

caching service-object query-optimization
Intermediate 5 steps
ruby
class Article < ApplicationRecord
  belongs_to :author, class_name: "User"
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

How scopes compose in Rails

scopes activerecord query-composition
Intermediate 8 steps
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1]
  def change
    create_table :order_items do |t|
      t.references :order, null: false, foreign_key: { on_delete: :cascade }

Enforcing order-item integrity in Rails

migrations foreign-keys validations
Intermediate 7 steps
ruby
class Registration < ApplicationRecord
  belongs_to :event
 
  validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }

Validating registrations in Rails

validations i18n error-handling
Intermediate 8 steps
ruby
class NewCommentNotifier < ApplicationNotifier
  deliver_by :database
 
  deliver_by :email do |config|

Multi-channel notifications with Noticed in Rails

notifications delivery-methods fan-out
Intermediate 6 steps
ruby
class DocumentsController < ApplicationController
  before_action :authenticate_user!
  before_action :set_document
 

Serving secure file downloads in Rails

authorization signed-urls active-storage
Intermediate 8 steps
ruby
class ApplicationJob < ActiveJob::Base
  retry_on ActiveRecord::Deadlocked, wait: 5.seconds, attempts: 3
  discard_on ActiveJob::DeserializationError
 

Instrumenting every job in Rails

active-job structured-logging retries
Intermediate 6 steps
ruby
class PasswordResetsController < ApplicationController
  RESET_PURPOSE = :password_reset
  RESET_EXPIRY = 15.minutes
 

Password resets with signed global IDs in Rails

authentication signed-tokens global-id
Intermediate 9 steps
ruby
module ProductsHelper
  def cached_product_row(product)
    cache [product, current_user.role] do
      render partial: "products/row", locals: { product: product }

Russian doll caching that busts itself in Rails

fragment-caching cache-invalidation associations
Intermediate 4 steps
ruby
class DigestMailer < ApplicationMailer
  default from: "notifications@example.com"
 
  def weekly_digest(user)

Building a weekly digest email in Rails

mailers active-record query-scopes
Intermediate 6 steps
ruby
class OrdersController < ApplicationController
  rescue_from ActiveRecord::RecordNotUnique, with: :handle_duplicate_submission
 
  def create

Idempotent order creation in Rails

idempotency database-constraints error-handling
Intermediate 8 steps
ruby
class InventoryItem < ApplicationRecord
  belongs_to :warehouse
 
  validates :quantity, numericality: { greater_than_or_equal_to: 0 }

Safe inventory updates in Rails

concurrency pessimistic-locking optimistic-locking
Advanced 7 steps
ruby
class PaymentMethod < ApplicationRecord
  belongs_to :account
 
  encrypts :card_number, deterministic: false

How Rails encrypts sensitive payment fields

encryption validation scopes
Intermediate 9 steps
ruby
class User < ApplicationRecord
  has_secure_password
 
  normalizes :email, with: ->(email) { email.strip.downcase }

Normalizing user input in Rails models

normalization validation data integrity
Intermediate 6 steps
ruby
class Account < ApplicationRecord
  has_many :projects, dependent: :destroy_async
  has_many :memberships, dependent: :destroy_async
  has_many :invoices, dependent: :restrict_with_error

Safely closing an Account in Rails

associations callbacks transactions
Intermediate 9 steps
ruby
require "csv"
 
class Api::V1::ProductImportsController < Api::V1::BaseController
  MAX_ROWS = 10_000

Bulk CSV imports with upsert_all in Rails

bulk-insert csv-parsing upsert
Intermediate 8 steps
ruby
class HealthController < ApplicationController
  skip_before_action :authenticate_user!, raise: false
  skip_forgery_protection
 

Building a health check endpoint in Rails

health-check monitoring error-handling
Intermediate 7 steps
ruby
module Instrumentation
  module Timing
    def self.[](*method_names)
      Module.new do

Timing methods with a prepended module in Ruby in Rails

metaprogramming prepend instrumentation
Advanced 7 steps