Code Explainers

Ruby on Rails code explainers

ruby
class WeeklySignupsReport
  DEFAULT_WEEKS = 12
 
  def initialize(weeks: DEFAULT_WEEKS, source: User.all)

Building a weekly signups report in Rails

service object aggregation group by
Intermediate 7 steps
ruby
class ApplicationController < ActionController::Base
  EXPERIMENTS = {
    checkout_button_color: %w[control blue green],
    onboarding_flow: %w[control streamlined]

How A/B test cohorts are assigned in Rails

a-b-testing cookies hashing
Intermediate 8 steps
ruby
class Coupon < ApplicationRecord
  has_many :redemptions, dependent: :destroy
 
  validates :code, presence: true, uniqueness: { case_sensitive: false }

Safe coupon redemption in Rails

validation contexts pessimistic locking scopes
Advanced 10 steps
ruby
class AdminConstraint
  def self.matches?(request)
    new(request).matches?
  end

How routing constraints gate admin routes in Rails

routing authorization constraints
Intermediate 8 steps
ruby
class ReverseGeocodeSignupJob < ApplicationJob
  queue_as :default
 
  retry_on Geocoder::OverQueryLimitError, wait: 5.minutes, attempts: 3

How Rails jobs handle reverse geocoding

background-jobs error-handling geocoding
Intermediate 7 steps
ruby
class SyncInventoryJob < ApplicationJob
  queue_as :integrations
 
  retry_on Faraday::TimeoutError,

Resilient background jobs with retry_on in Rails

background-jobs error-handling retries
Intermediate 8 steps
ruby
module MarkdownHelper
  ALLOWED_TAGS = %w[
    p br strong em del a ul ol li blockquote code pre
    h1 h2 h3 h4 h5 h6 hr img table thead tbody tr th td

Safely rendering Markdown in a Rails helper

sanitization markdown security
Intermediate 8 steps
ruby
class ActivityFeed
  include Enumerable
 
  Entry = Struct.new(:record, :type, :occurred_at, keyword_init: true) do

Building a paginated activity feed in Rails

enumerable pagination composition
Intermediate 9 steps
ruby
class Current < ActiveSupport::CurrentAttributes
  attribute :user, :request_id, :user_agent, :ip_address
 
  resets { Time.zone = nil }

Per-request audit trails with Current in Rails

thread-local-state auditing concerns
Intermediate 8 steps
ruby
class Category < ApplicationRecord
  belongs_to :parent, class_name: "Category", optional: true
  has_many :children,
           -> { order(:position) },

Modeling a self-referential category tree in Rails

self-referential-association recursion tree-structure
Intermediate 9 steps
ruby
class ReportingQuery
  def initialize(scope = ApplicationRecord)
    @scope = scope
  end

Routing heavy reports to a read replica in Rails

read-replica database-roles query-object
Intermediate 6 steps
ruby
class WeatherLookup
  Result = Struct.new(:temperature, :conditions, keyword_init: true)
 
  class TimeoutError < StandardError; end

A resilient weather API service object in Rails

service-object http-client error-handling
Intermediate 7 steps
ruby
class Post < ApplicationRecord
  belongs_to :author, counter_cache: false
  has_many :comments, dependent: :destroy
end

A custom counter cache in Rails

counter-cache callbacks associations
Intermediate 7 steps
ruby
namespace :active_storage do
  desc "Purge blobs that have been unattached for more than 48 hours"
  task purge_stale: :environment do
    cutoff = 48.hours.ago

A Rake task to purge stale Active Storage blobs in Rails

rake active-storage batch-processing
Intermediate 8 steps
ruby
class Article < ApplicationRecord
  belongs_to :author
  has_many :taggings, dependent: :destroy
  has_many :tags, through: :taggings

Keeping a search index fresh in Rails

callbacks background-jobs debounce
Intermediate 9 steps
ruby
class ApplicationController < ActionController::Base
  INACTIVITY_TIMEOUT = 30.minutes
 
  before_action :expire_stale_session

Idle session timeout in a Rails controller

authentication session-management before-action
Intermediate 6 steps
ruby
class ChatChannel < ApplicationCable::Channel
  periodically :sweep_stale_typists, every: 3.seconds
 
  def subscribed

How a typing indicator works in Rails ActionCable

websockets presence cache-expiry
Intermediate 9 steps
ruby
class Author < ApplicationRecord
  has_many :posts
 
  scope :with_post_stats, -> {

Aggregating post stats in a Rails scope

scopes sql-aggregation left-join
Intermediate 8 steps