ruby
class PriceBreakdown < Struct.new(:subtotal_cents, :discount_cents, :tax_cents, keyword_init: true)
  def initialize(*)
    super
    freeze
  end

Memoizing a Pricing Breakdown as an Immutable Value Object in Rails

rails memoization value-object
by codesnips 3 tabs
php
<?php

namespace App\Dto;

use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\Validator\Constraints as Assert;

Symfony Avatar Upload: Constrained Form Type, Image Validation, and an Uploader Service

symfony forms validation
by codesnips 4 tabs
rust
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Interval {
    pub start: i64,
    pub end: i64,
}

Merging Overlapping Booking Intervals with a Sweep-Line in Rust

rust algorithms intervals
by codesnips 3 tabs
typescript
import { useEffect, useState } from 'react';

export function useLocalStorage<T>(
  key: string,
  initialValue: T
): [T, (value: T) => void] {

Persisting a Dark-Mode Theme Toggle with a React ThemeProvider and localStorage

react context hooks
by codesnips 4 tabs
javascript
class BatchLoader {
  constructor(batchFn, { cacheKeyFn = (k) => k } = {}) {
    this.batchFn = batchFn;
    this.cacheKeyFn = cacheKeyFn;
    this.cache = new Map();
    this.queue = [];

Coalescing Concurrent Reads with a DataLoader-Style Batch Loader in Node

dataloader batching graphql
by codesnips 3 tabs
java
@Component
public class SalesRollupScheduler {

    private static final Logger log = LoggerFactory.getLogger(SalesRollupScheduler.class);
    private static final int ROLLUP_WINDOW_DAYS = 3;

Roll Up Daily Sales Totals With a Scheduled Spring Batch Upsert via JdbcTemplate

spring-boot jdbctemplate postgres
by codesnips 3 tabs
python
from dataclasses import dataclass, field
from datetime import datetime, timezone
from decimal import Decimal


def _now():

Synchronous Domain Event Bus with a Registry-Based Publisher in Python

domain-events event-bus pubsub
by codesnips 3 tabs
go
package scheduler

import (
	"context"
	"log"
	"sync"

Graceful Cron-Style Scheduler in Go With Ticker and Context Cancellation

scheduler ticker context
by codesnips 3 tabs
ruby
class InventoryLevel < ApplicationRecord
  belongs_to :warehouse

  UPSERT_COLUMNS = %w[warehouse_id sku on_hand reserved updated_at].freeze

  def self.upsert_counts(rows)

Bulk-Upsert Inventory Counts in One Query From a Sidekiq Job

rails postgres upsert
by codesnips 3 tabs
python
from alembic import op
import sqlalchemy as sa

revision = "20240612_add_status"
down_revision = "20240515_create_orders"
branch_labels = None

Zero-Downtime NOT NULL Column Backfill with Alembic and SQLAlchemy

alembic sqlalchemy migrations
by codesnips 2 tabs
ruby
class User < ApplicationRecord
  normalizes :phone, with: ->(value) { PhoneNormalizer.call(value) }, apply_to_nil: false

  validates :phone,
            presence: true,
            uniqueness: { case_sensitive: false },

Normalizing Phone Numbers on Assignment with Rails normalizes and a Custom Serializer

rails activerecord normalization
by codesnips 3 tabs
typescript
import { useMemo } from "react";

export type SortDir = "asc" | "desc";
export interface SortConfig<T> {
  key: keyof T;
  dir: SortDir;

Memoized Async Search With a Cached Selector Hook in React

react hooks usememo
by codesnips 3 tabs