Code Explainers

Ruby on Rails code explainers

ruby
module Api
  module Reports
    class DailyOrderTotalsController < Api::BaseController
      def index

Building a daily order totals report in Rails

sql aggregation json api query building
Intermediate 7 steps
ruby
module Authenticatable
  extend ActiveSupport::Concern
 
  included do

JWT authentication as a Rails concern

authentication jwt concerns
Intermediate 6 steps
ruby
class Contact < ApplicationRecord
  PHONE_FORMATS = {
    "US" => /\A\+1\d{10}\z/,
    "GB" => /\A\+44\d{10}\z/,

Country-aware phone validation in Rails

validation callbacks regex
Intermediate 6 steps
ruby
class ProjectsController < ApplicationController
  before_action :set_project, only: %i[show update destroy]
 
  def create

Scoping a Rails API controller to Current.account

multitenancy strong-parameters nested-attributes
Intermediate 7 steps
ruby
class SearchController < ApplicationController
  def index
    @query = params[:q].to_s.strip
  end

Live search suggestions in a Rails controller

controllers sql-injection query-building
Intermediate 6 steps
ruby
class TasksController < ApplicationController
  before_action :set_project
 
  def reorder

Bulk task reordering with upsert_all in Rails

bulk-update upsert authorization
Intermediate 8 steps
ruby
class Product < ApplicationRecord
  belongs_to :category, touch: true
 
  has_many :reviews, dependent: :destroy

How Rails models wire up associations

active record associations validations
Intermediate 7 steps
ruby
module SlowQueryLogger
  SLOW_QUERY_THRESHOLD_MS = 200.0
  IGNORED_PAYLOAD_NAMES = %w[SCHEMA TRANSACTION].freeze
 

Logging slow SQL queries in Rails

instrumentation logging pub-sub
Intermediate 7 steps
ruby
class PaymentGateway
  class MissingCredentialError < StandardError; end
 
  def initialize(env: Rails.env)

Wrapping Rails credentials in a gateway

encapsulation credentials error handling
Intermediate 6 steps
ruby
class WelcomeSequenceOrchestrator
  STEPS = [
    { mailer: :welcome_email,      delay: 0.hours },
    { mailer: :getting_started,    delay: 1.day },

Scheduling a drip email sequence in Rails

mailers background jobs scheduling
Intermediate 6 steps
ruby
class SyncContactsJob < ApplicationJob
  queue_as :external_api
 
  MAX_CONCURRENCY = 5

Rate-limited CRM sync in a Rails job

background-jobs rate-limiting redis
Advanced 9 steps
ruby
class Admin::OrdersExportController < Admin::BaseController
  include ActionController::Live
 
  def show

Streaming a CSV export in Rails

streaming csv-export batching
Advanced 8 steps
ruby
class DatasetImportJob < ApplicationJob
  queue_as :default
 
  def perform(import)

Streaming import progress with a Rails job

background-jobs turbo-streams progress-tracking
Intermediate 9 steps
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 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 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