Code Explainers

Ruby code explainers

ruby
def build_tree(rows, root_id: nil)
  children_by_parent = Hash.new { |hash, key| hash[key] = [] }
 
  rows.each do |row|

Building a tree from flat rows in Ruby

recursion hash-grouping tree-structure
Intermediate 5 steps
ruby
class MetricSeries
  def initialize(readings, window: 5)
    @readings = readings
    @window = window

Rolling averages with each_cons in Ruby

sliding-window enumerable data-smoothing
Intermediate 7 steps
ruby
class Api::V1::ArticlesController < Api::V1::BaseController
  def index
    articles = Article
      .published

Building a JSON:API endpoint in Rails

serialization eager-loading pagination
Intermediate 7 steps
ruby
class FundsTransfer
  class InsufficientFundsError < StandardError; end
 
  def initialize(source:, destination:, amount:)

Atomic money transfers with Rails transactions

service object database transactions row locking
Advanced 9 steps
ruby
class Money
  include Comparable
 
  CURRENCY_SYMBOLS = { usd: "$", eur: "€", gbp: "£" }.freeze

Building an immutable Money value object in Ruby

value-object immutability comparable
Intermediate 8 steps
ruby
require "csv"
 
class SalesReport
  def initialize(path)

Aggregating CSV sales data in Ruby

data-aggregation memoization group_by
Intermediate 6 steps
ruby
module DurationFormatter
  UNITS = [
    ['week', 604_800],
    ['day', 86_400],

Turning seconds into human-readable durations in Ruby

greedy-decomposition modular-arithmetic formatting
Intermediate 7 steps
ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"
 

Live-updating comments with Turbo in Rails

turbo-streams callbacks associations
Intermediate 8 steps
ruby
require 'json'
require 'set'
 
class SensitiveScrubber

Recursively scrubbing secrets from JSON

recursion data-masking pattern-matching
Intermediate 7 steps
ruby
class ReportBatcher
  BATCH_SIZE = 500
 
  def initialize(account)

Batching monthly email summaries in Rails

batching service-object background-jobs
Intermediate 7 steps
ruby
class Comment < ApplicationRecord
  belongs_to :commentable, polymorphic: true, counter_cache: true
  belongs_to :author, class_name: "User"
 

How polymorphic comments work in Rails

polymorphic-association concerns counter-cache
Intermediate 8 steps
ruby
class SessionsController < ApplicationController
  MAX_ATTEMPTS = 5
  THROTTLE_WINDOW = 15.minutes
 

Throttling failed logins in Rails

rate-limiting authentication caching
Intermediate 7 steps
ruby
class ProductsController < ApplicationController
  def index
    @products = Product
      .includes(:category, :brand)

Building a safe filterable product index in Rails

query objects scopes strong parameters
Intermediate 8 steps
ruby
module LogParser
  class AccessLogStreamer
    SEVERITY_PATTERN = /\b(ERROR|WARN|FATAL)\b/
 

Streaming log lines with a Ruby enumerator

enumerators lazy-iteration regex-matching
Intermediate 6 steps
ruby
class HostnameValidator < ActiveModel::EachValidator
  MAX_LENGTH = 253
  LABEL = /\A(?!-)[a-z0-9-]{1,63}(?<!-)\z/i
 

Writing a custom hostname validator in Rails

validation custom validator regex
Intermediate 8 steps
ruby
class PaymentsController < ApplicationController
  before_action :require_idempotency_key
 
  def create

Idempotent payment creation in Rails

idempotency transactions race-conditions
Advanced 10 steps
ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  has_many :respondents, dependent: :nullify
 

Nested survey forms in Rails

nested-attributes validations associations
Intermediate 9 steps
ruby
class OrderConfirmationJob < ApplicationJob
  queue_as :mailers
 
  retry_on Net::OpenTimeout, wait: :polynomially_longer, attempts: 5

Resilient background jobs in Rails

background-jobs retries idempotency
Intermediate 8 steps