Code Explainers

Ruby code explainers

ruby
class Booking < ApplicationRecord
  belongs_to :room
  belongs_to :guest
 

Guarding booking dates in a Rails model

validations associations scopes
Intermediate 5 steps
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 LRUCache
  def initialize(capacity)
    raise ArgumentError, "capacity must be positive" unless capacity.positive?
 

How an LRU cache works in Ruby

caching eviction hash-ordering
Intermediate 7 steps
ruby
class QueryParser
  def self.parse(query_string)
    new(query_string).parse
  end

Parsing nested query strings in Ruby

parsing recursion tokenization
Intermediate 9 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 Order
  class InvalidTransition < StandardError; end
 
  TRANSITIONS = {

A state machine for order transitions in Ruby

state-machine data-driven error-handling
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 ApacheLogParser
  LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/
 
  TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"

Parsing Apache logs with named captures

regex named-captures parsing
Intermediate 6 steps
ruby
require "csv"
 
def parse_transaction_row(line)
  fields = CSV.parse_line(line, headers: false, skip_blanks: true)

Parsing one CSV transaction row in Ruby

parsing type-coercion error-handling
Intermediate 6 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
require "bigdecimal"
 
module Money
  CENTS = BigDecimal("0.01")

Handling money safely with BigDecimal in Ruby

bigdecimal rounding currency
Intermediate 7 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
require "yaml"
require "pathname"
 
class AppConfig

A typed config loader in Ruby

yaml configuration recursion
Intermediate 8 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
def build_pivot_table(sales)
  pivot = sales.each_with_object(Hash.new { |h, k| h[k] = Hash.new(0.0) }) do |record, table|
    region = record.fetch(:region)
    quarter = record.fetch(:quarter)

Building a pivot table in Ruby

aggregation nested-hashes default-values
Intermediate 9 steps