Code Explainers

Ruby code explainers

ruby
module UniqueJob
  extend ActiveSupport::Concern
 
  class_methods do

Deduplicating Active Job enqueues in Rails

concurrency idempotency caching
Advanced 9 steps
ruby
class OrderMailerPreview < ActionMailer::Preview
  def confirmation
    OrderMailer.confirmation(sample_order)
  end

Previewing Rails mailers with sample data

mailer-previews test-fixtures in-memory-objects
Beginner 6 steps
ruby
def render_table(rows)
  return "(no data)" if rows.empty?
 
  columns = rows.flat_map(&:keys).uniq

Rendering an ASCII table in Ruby

text-formatting column-alignment recursion
Intermediate 8 steps
ruby
class ApplicationController < ActionController::Base
  ALLOWED_REDIRECT_HOSTS = [nil, ENV.fetch("APP_HOST", "app.example.com")].freeze
 
  def store_return_to(location = request.fullpath)

Safe post-login redirects in Rails

open-redirect session authentication
Intermediate 9 steps
ruby
require 'set'
 
class DirectoryWatcher
  def initialize(path, pattern: '**/*', interval: 1.0)

Polling for file changes in Ruby

polling filesystem diffing
Intermediate 7 steps
ruby
class HashDiff
  Change = Struct.new(:from, :to)
 
  def self.call(before, after)

Diffing two hashes in Ruby

set-operations struct enumerable
Intermediate 7 steps
ruby
module CreditCard
  module_function
 
  def valid?(number)

Validating credit card numbers with Luhn

checksum luhn-algorithm validation
Intermediate 6 steps
ruby
class UserColor
  GOLDEN_RATIO_CONJUGATE = 0.618033988749895
 
  def initialize(username)

Deriving a stable color from a username

hashing color-theory deterministic-mapping
Intermediate 7 steps
ruby
namespace :counter_cache do
  desc "Recalculate comments_count for posts after a backfill"
  task warm_post_comments: :environment do
    scope = Post.where(comments_count: nil).or(Post.where("comments_count < 0"))

Backfilling counter caches in a Rake task in Rails

counter-cache batching rake-tasks
Intermediate 6 steps
ruby
class ToastBroadcaster
  include ActionView::RecordIdentifier
 
  def self.broadcast_to(user, message:, type: :notice)

How Turbo Stream toasts broadcast in Rails

turbo-streams service-object real-time
Intermediate 6 steps
ruby
class TemplateInterpolator
  PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/
 
  def initialize(strict: false)

Interpolating templates with dotted keys in Ruby

regex string-interpolation hash-traversal
Intermediate 6 steps
ruby
class KeyTransformer
  def self.camelize(data)
    new.camelize(data)
  end

Recursively camelizing nested Ruby data

recursion data-transformation pattern-matching
Intermediate 7 steps
ruby
module Paginatable
  extend ActiveSupport::Concern
 
  private

A reusable pagination concern in Rails

pagination concerns http-headers
Intermediate 8 steps
ruby
class Api::MessagesController < ApiController
  before_action :authenticate_api_key!
 
  rate_limit to: 100,

Layered API rate limiting in Rails

rate-limiting api-authentication throttling
Intermediate 9 steps
ruby
class Order < ApplicationRecord
  include AASM
 
  belongs_to :warehouse

Modeling an order lifecycle with AASM in Rails

state machine guards callbacks
Intermediate 10 steps
ruby
require "timeout"
require "net/http"
 
class RemoteInventoryClient

Bounding a slow HTTP call with Timeout in Ruby

timeout error-handling http
Intermediate 6 steps
ruby
require "base64"
require "json"
 
module Attachment

Packing binary attachments into JSON

serialization base64 json
Intermediate 8 steps
ruby
require "yaml"
 
class FrontMatter
  DELIMITER = /\A---\s*\n(.*?)\n---\s*\n?(.*)\z/m

Parsing YAML front matter in Ruby

parsing regular-expressions yaml
Intermediate 8 steps