ruby

ruby
class Post < ApplicationRecord
  # View counter - increments without hitting the database
  kredis_counter :view_count, expires_in: 1.day

  # Recent viewers list - stores last 10 viewer IDs
  kredis_unique_list :recent_viewers, limit: 10

Rails Kredis for higher-level Redis operations

rails redis kredis
by Maya Patel 2 tabs
ruby
module Idempotency
  extend ActiveSupport::Concern

  included do
    before_action :check_idempotency_key, only: [:create, :update]
    after_action :store_idempotent_response, only: [:create, :update]

Request deduplication with idempotency keys

rails api reliability
by Alex Kumar 1 tab
ruby
base_path = Rails.root.join('storage', 'exports').realpath
requested = base_path.join(params[:filename].to_s).cleanpath

unless requested.to_s.start_with?(base_path.to_s) && requested.file?
  raise ActionController::RoutingError, 'Not Found'
end

Preventing path traversal in download endpoints

path-traversal file-security secure-coding
by Kai Nakamura 1 tab
ruby
# Simple mixin
module Loggable
  def log(message)
    puts "[#{Time.now}] #{self.class.name}: #{message}"
  end
end

Module mixins and concerns for code reuse

ruby modules mixins
by Sarah Mitchell 3 tabs
ruby
module Api
  module V1
    class PostsController < ApplicationController
      def create
        post = current_user.posts.build(post_params)

Rails strong parameters for nested attributes

rails security strong-parameters
by Maya Patel 1 tab
ruby
class CreateMaintenanceTasks < ActiveRecord::Migration[7.0]
  def change
    create_table :maintenance_tasks do |t|
      t.string :name, null: false
      t.string :state, null: false, default: "pending"
      t.datetime :started_at

Database-Backed “Run Once” Migrations for Maintenance Tasks

rails migrations background-jobs
by codesnips 3 tabs
ruby
class CreateEmailDeliveries < ActiveRecord::Migration[7.1]
  def change
    create_table :email_deliveries do |t|
      t.string :dedupe_key, null: false
      t.string :mailer, null: false
      t.string :action, null: false

Transactional Email “Send Once” with Delivered Marker

rails reliability activerecord
by codesnips 4 tabs
ruby
require "faraday"
require "faraday/retry"

module Http
  class RetryableError < StandardError; end
  class CircuitOpenError < StandardError; end

HTTP Timeouts + Retries Wrapper (Faraday)

rails http reliability
by codesnips 3 tabs
yaml
:concurrency: 10
:queues:
  - [critical, 4]
  - [default, 2]
  - [low, 1]

Background jobs with Sidekiq and reliable queues

rails sidekiq background-jobs
by Alex Kumar 2 tabs
ruby
class SupportMailbox < ApplicationMailbox
  def process
    ticket = Ticket.find_or_create_by!(message_id: mail.message_id) do |t|
      t.subject = mail.subject
      t.from_email = mail.from&.first
      t.body = mail.decoded

Action Mailbox: broadcast incoming emails into a feed

rails hotwire turbo
by Henry Kim 3 tabs
ruby
FactoryBot.define do
  factory :post do
    association :author, factory: :user
    sequence(:title) { |n| "Post Title #{n}" }
    body { Faker::Lorem.paragraphs(number: 3).join("\n\n") }
    status { :draft }

Rails fixtures vs factories for test data

rails testing fixtures
by Maya Patel 2 tabs
ruby
class AtLeastOneOfValidator < ActiveModel::Validator
  def validate(record)
    fields = Array(options[:fields])
    raise ArgumentError, "provide :fields" if fields.empty?

    return if fields.any? { |field| filled?(record.public_send(field)) }

Custom Validator for “At Least One of” Fields

rails activemodel validations
by codesnips 3 tabs