ruby

ruby
class Customer < ApplicationRecord
  encrypts :phone_number
  encrypts :external_token, deterministic: true
end

ActiveRecord Encryption for PII Fields

rails security encryption
by Sarah Chen 1 tab
ruby
class Collection < ApplicationRecord
  has_many :memberships

  def self.visible_to(member)
    collections = arel_table
    memberships = Membership.arel_table

Polymorphic “Visible To” Scope with Arel

rails activerecord arel
by Sarah Chen 1 tab
ruby
class UserRegistrationService
  class Result
    attr_reader :user, :errors

    def initialize(success:, user: nil, errors: [])
      @success = success

Service objects for business logic encapsulation

ruby rails service-objects
by Sarah Mitchell 2 tabs
ruby
class ViewCounter
  def bump(snip_id)
    Redis.current.incr("snip:views:#{snip_id}")
  end
end

Lock-Free Read Pattern for Hot Counters (Approximate)

rails redis performance
by Sarah Chen 2 tabs
ruby
class ReindexCheckpoint < ApplicationRecord
  validates :name, presence: true, uniqueness: true
end

Safer Background Reindex: slice batches + checkpoints

rails search operations
by Sarah Chen 2 tabs
ruby
class Inventory::Reserve
  class NotEnoughStock < StandardError; end

  def initialize(sku:, quantity:)
    @sku = sku
    @quantity = Integer(quantity)

Transactional “Reserve Inventory” with SELECT … FOR UPDATE

rails activerecord transactions
by Sarah Chen 1 tab
ruby
module ApiErrorHandler
  extend ActiveSupport::Concern

  included do
    rescue_from StandardError, with: :handle_standard_error
    rescue_from ActiveRecord::RecordNotFound, with: :handle_not_found

Structured JSON error responses

rails api error-handling
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class PostsController < BaseController
      def index
        # Eager load author and recent comments with their authors
        posts = Post.published

N+1 prevention with includes and preload

rails activerecord performance
by Alex Kumar 1 tab
ruby
module ReadYourWrites
  TTL = 10

  def pin_primary!
    session[:pin_primary_until] = Time.current.to_i + TTL
  end

“Read Your Writes” Consistency: Pin to Primary After POST

rails replicas consistency
by Sarah Chen 2 tabs
ruby
class NormalizeHeadlines
  def call
    Member.select(:id, :headline).find_each do |m|
      normalized = m.headline.to_s.strip.gsub(/ +/, ' ')
      next if normalized == m.headline

“Write Amplification” Guard: Only Update Changed Columns

rails activerecord performance
by Sarah Chen 1 tab
ruby
# Define refinements in a module
module StringExtensions
  refine String do
    def titleize
      split.map(&:capitalize).join(' ')
    end

Ruby refinements for scoped monkey patching

ruby refinements monkey-patching
by Sarah Mitchell 2 tabs
ruby
module TagNormalization
  extend ActiveSupport::Concern

  included do
    before_validation :normalize_tag_list
  end

Normalize Tags at Write Time

rails tags data-quality
by Sarah Chen 1 tab