activerecord

ruby
module StatementTimeout
  extend ActiveSupport::Concern

  class TimeoutExceeded < StandardError; end

  def with_statement_timeout(milliseconds)

Guard Against Slow Queries with statement_timeout

rails postgres performance
by codesnips 3 tabs
ruby
module DangerousAction
  extend ActiveSupport::Concern

  FRESH_WINDOW = 10.minutes

  class ConfirmationMismatch < StandardError; end

Guard Rails for Dangerous Admin Actions

rails admin security
by codesnips 3 tabs
ruby
require "loofah"

class HtmlSanitizer
  ALLOWED_TAGS  = %w[p br a strong em ul ol li blockquote code pre h2 h3].freeze
  ALLOWED_ATTRS = %w[href title].freeze
  SAFE_SCHEMES  = %w[http https mailto].freeze

Safer HTML Sanitization Pipeline

rails security xss
by codesnips 4 tabs
yaml
production:
  primary:
    adapter: postgresql
    database: app_production
    username: app
    password: <%= ENV["PRIMARY_DB_PASSWORD"] %>

Read Replica Routing for GET-Heavy Endpoints

rails activerecord postgres
by codesnips 4 tabs
ruby
class OrderCreationService
  Result = Struct.new(:success?, :order, :error, keyword_init: true)

  def initialize(customer:, line_params:)
    @customer = customer
    @line_params = line_params

Transactional Order Creation With Nested Savepoints in Rails

rails activerecord postgres
by codesnips 3 tabs
ruby
class AddSoftDeleteToDocuments < ActiveRecord::Migration[7.0]
  disable_ddl_transaction!

  def change
    add_column :documents, :marked_for_deletion_at, :datetime, null: true

Safer Time-Based Deletes with “mark then sweep”

rails reliability activerecord
by codesnips 4 tabs
ruby
class Comment < ApplicationRecord
  belongs_to :post
  belongs_to :author, class_name: "User"

  validates :body, presence: true, length: { maximum: 5_000 }

Declarative model broadcasts with broadcasts_to (Rails 7)

rails hotwire turbo
by codesnips 4 tabs
ruby
class CreateAccountsAndLedger < ActiveRecord::Migration[7.1]
  def change
    create_table :accounts do |t|
      t.string :name, null: false
      t.string :currency, null: false, default: "USD"
      t.bigint :balance_cents, null: false, default: 0

Atomic Account Transfers in Rails With Row Locks and a Balance Service

rails postgres transactions
by codesnips 4 tabs
ruby
class CreateIdempotencyKeys < ActiveRecord::Migration[7.1]
  def change
    create_table :idempotency_keys do |t|
      t.string :key, null: false
      t.string :request_path, null: false
      t.datetime :locked_at

Idempotent Form Submissions in Rails with an Idempotency-Key Column and before_action Guard

rails idempotency postgres
by codesnips 4 tabs
ruby
module ConnectionHealth
  extend ActiveSupport::Concern

  def with_fresh_connection
    conn = ActiveRecord::Base.connection
    conn.verify! # pings and reconnects if the socket is dead

Keep DB Connections Healthy in Long Jobs

rails activerecord background-jobs
by codesnips 3 tabs
ruby
class Order < ApplicationRecord
  has_many :line_items, dependent: :destroy, inverse_of: :order

  accepts_nested_attributes_for :line_items,
    reject_if: :all_blank,
    allow_destroy: true

Transactionally Create Parent + Children with accepts_nested_attributes_for

rails activerecord nested-attributes
by codesnips 3 tabs
ruby
class Cart < ApplicationRecord
  TTL = 30.minutes

  has_many :line_items, dependent: :destroy

  enum status: { active: 0, expired: 1, checked_out: 2 }

Expiring Idle Shopping Carts with a TTL Check and a Sweeper Job in Rails

rails background-jobs sidekiq
by codesnips 3 tabs