Code Explainers

Ruby code explainers

ruby
require 'optparse'
require 'ostruct'
 
def parse_options(argv)

Parsing CLI options with OptionParser

cli argument-parsing validation
Intermediate 8 steps
ruby
module Retryable
  class RetriesExhausted < StandardError; end
 
  RETRYABLE_ERRORS = [

Exponential backoff retries in Ruby

retry-logic exponential-backoff error-handling
Intermediate 7 steps
ruby
class Throttle
  def initialize(interval)
    @interval = interval
    @mutex = Mutex.new

A thread-safe throttle in Ruby

concurrency rate-limiting mutex
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
ruby
class ProductCatalog
  def featured_products
    Rails.cache.fetch("catalog/featured_products", expires_in: 12.hours) do
      Product.where(featured: true)

Caching patterns with Rails.cache.fetch

caching cache-keys expiry
Intermediate 5 steps
ruby
class RegistrationForm
  include ActiveModel::Model
  include ActiveModel::Attributes
 

How a Rails form object spans two models

form object validations transactions
Intermediate 7 steps
ruby
# Curry a multi-argument lambda so it can be applied one argument at a time.
add = ->(a, b, c) { a + b + c }
 
# Proc#curry returns a curried version that collects arguments incrementally.

Currying lambdas and methods in Ruby

currying closures partial-application
Intermediate 7 steps
ruby
class ThreadSafeCounter
  def initialize(initial = 0)
    @count = initial
    @mutex = Mutex.new

A thread-safe counter with Mutex in Ruby

concurrency mutex thread-safety
Intermediate 6 steps
ruby
# Binary search using Ruby's built-in Array#bsearch.
#
# There are two modes:
#   1. find-minimum mode  -> block returns true/false (monotonic)

Binary search patterns with Ruby's bsearch

binary-search algorithms ranges
Intermediate 7 steps
ruby
class LinkedList
  include Enumerable
 
  Node = Struct.new(:value, :next_node)

Building an enumerable linked list in Ruby

linked-list enumerable data-structures
Intermediate 7 steps
ruby
module FileResource
  # Opens a file, yields it to the caller, and guarantees the
  # handle is closed even if the block raises an exception.
  def self.open(path, mode = "r")

Guaranteeing cleanup with begin/ensure in Ruby

resource-management exception-safety blocks
Intermediate 8 steps