ruby

ruby
module CollectionCacheKey
  extend ActiveSupport::Concern

  def cache_key_for(scope)
    relation = scope.respond_to?(:all) ? scope.all : scope
    model = relation.klass

Deterministic Cache Keys for Collections

rails caching activerecord
by codesnips 3 tabs
ruby
class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id, dependent: :destroy

  before_validation :normalize_email
  before_create :generate_auth_token
  after_create :send_welcome_email

ActiveRecord callbacks for lifecycle hooks

rails activerecord patterns
by Alex Kumar 1 tab
ruby
class ApplicationController < ActionController::Base
  layout -> { turbo_frame_request? ? false : 'application' }
end

Render without layout for Turbo Frame requests

rails hotwire turbo
by Henry Kim 2 tabs
ruby
class AddUniqueIndexToTags < ActiveRecord::Migration[7.1]
  disable_ddl_transaction!

  def up
    execute <<~SQL
      UPDATE tags SET name = LOWER(TRIM(name)) WHERE name IS NOT NULL;

Safer “find or create” with Unique Constraint + Retry

rails activerecord concurrency
by codesnips 3 tabs
ruby
class Api::BaseController < ActionController::API
  rescue_from Devise::MissingWarden do
    head :unauthorized
  end
end

Handle 401 responses in Turbo by forcing a full redirect

rails hotwire turbo
by Henry Kim 2 tabs
ruby
class ExplainAnalyzer
  def initialize(relation, watched_tables:)
    @relation = relation
    @watched_tables = Array(watched_tables).map(&:to_s)
  end

Fast Fail for Missing Indexes (EXPLAIN sanity check)

rails postgres performance
by codesnips 3 tabs
ruby
class NotificationsController < ApplicationController
  def mark_all_read
    current_member.notifications.unread.update_all(read_at: Time.current)

    streams = Turbo::Streams::TagBuilder.new(view_context)

Build Turbo Stream responses in the controller (TagBuilder)

rails hotwire turbo
by Henry Kim 2 tabs
ruby
Rails.application.configure do
  # Bullet configuration
  config.after_initialize do
    Bullet.enable = true
    Bullet.alert = true # Show JavaScript alert
    Bullet.bullet_logger = true # Log to bullet.log

Rails N+1 query detection with Bullet

rails performance n-1
by Maya Patel 3 tabs
ruby
class UserRegistrationForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :email, :string
  attribute :name, :string

Form objects for complex form handling

ruby rails form-objects
by Sarah Mitchell 2 tabs
erb
<%= form_with model: @post, url: preview_posts_path, data: { turbo_frame: 'preview' } do |f| %>
  <%= f.text_area :body, rows: 10, class: 'w-full rounded border p-2' %>
  <%= f.submit 'Preview', class: 'mt-2 rounded bg-gray-100 px-3 py-1' %>
<% end %>

<%= turbo_frame_tag 'preview' do %>

Inline markdown preview using Turbo Frames

rails hotwire turbo
by Henry Kim 2 tabs
erb
<!DOCTYPE html>
<html>
  <head>
    <title>Contacts</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

Turbo Frames modal: load, submit, then close via stream

rails turbo hotwire
by codesnips 4 tabs
ruby
module RetryableTransaction
  module_function

  RETRIABLE = [ActiveRecord::Deadlocked, ActiveRecord::LockWaitTimeout].freeze

  def run(max_retries: 3, base_delay: 0.05, &block)

Deadlock-Aware Retry Wrapper

rails postgres reliability
by codesnips 3 tabs