rails

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 ShardedCounter
  SHARDS = 16
  SNAPSHOT_TTL = 10 # seconds

  def initialize(name, redis: REDIS)
    @name = name

Lock-Free Read Pattern for Hot Counters (Approximate)

rails redis performance
by codesnips 3 tabs
ruby
class ReindexCheckpoint < ApplicationRecord
  enum status: { idle: 0, running: 1, done: 2, failed: 3 }

  validates :index_name, presence: true, uniqueness: true

  def self.for(index_name)

Safer Background Reindex: slice batches + checkpoints

rails reliability elasticsearch
by codesnips 4 tabs
ruby
class CreateInventoryReservations < ActiveRecord::Migration[7.1]
  def change
    create_table :inventory_items do |t|
      t.string  :sku, null: false
      t.integer :quantity_on_hand,  null: false, default: 0
      t.integer :quantity_reserved, null: false, default: 0

Transactional “Reserve Inventory” with SELECT … FOR UPDATE

rails activerecord transactions
by codesnips 3 tabs
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 Middleware
  class DatabasePinning
    PIN_WINDOW = 5.seconds

    def initialize(app)
      @app = app

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

rails consistency reliability
by codesnips 4 tabs
ruby
module WriteAmplificationGuard
  extend ActiveSupport::Concern

  def update_if_changed(attrs)
    changed = attrs.each_with_object({}) do |(key, value), acc|
      cast = self.class.type_for_attribute(key.to_s).cast(value)

“Write Amplification” Guard: Only Update Changed Columns

rails activerecord performance
by codesnips 3 tabs
ruby
class DocumentsController < ApplicationController
  before_action :set_document, only: :destroy

  def destroy
    @document.discard!

Undo delete with a Turbo Stream “restore” action

rails hotwire turbo-streams
by codesnips 4 tabs
ruby
class CreateTags < ActiveRecord::Migration[7.0]
  def change
    create_table :tags do |t|
      t.string :name, null: false
      t.integer :taggings_count, null: false, default: 0
      t.timestamps

Normalize Tags at Write Time

rails activerecord callbacks
by codesnips 3 tabs
ruby
class JsonLogFormatter < ActiveSupport::Logger::SimpleFormatter
  def call(severity, timestamp, _progname, message)
    if message.is_a?(Hash)
      entry = {
        ts: timestamp.utc.iso8601(3),
        level: severity

Lograge-Style JSON Logging Without Extra Gems

rails logging observability
by codesnips 3 tabs
ruby
class Rack::Attack
  Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new(url: ENV['REDIS_URL'])

  safelist('allow-localhost') do |req|
    req.ip == '127.0.0.1' || req.ip == '::1'
  end

Rate limiting with Redis and Rack::Attack

rails security redis
by Alex Kumar 1 tab