Code Explainers

Browse the library

ruby
class Survey < ApplicationRecord
  has_many :questions, dependent: :destroy
  has_many :respondents, dependent: :nullify
 

Nested survey forms in Rails

nested-attributes validations associations
Intermediate 9 steps
php
<?php
 
namespace App\Security;
 

Secure password hashing with Argon2id in PHP

password-hashing argon2id timing-attacks
Intermediate 8 steps
python
import time
import threading
 
 

How a thread-safe token bucket rate limiter works

rate-limiting concurrency locking
Intermediate 6 steps
go
package logfmt
 
import (
	"bytes"

Pooling buffers for logfmt encoding in Go

object-pooling memory-reuse serialization
Intermediate 8 steps
typescript
import { z } from "zod";
 
const ProductQuerySchema = z.object({
  page: z.coerce.number().int().positive().default(1),

Validating URL query params with Zod

validation schema type-inference
Intermediate 8 steps
java
public final class RegistrationValidator {
 
    private static final Pattern EMAIL = Pattern.compile("^[\\w.+-]+@[\\w-]+\\.[\\w.-]+$");
    private static final Pattern USERNAME = Pattern.compile("^[a-zA-Z0-9_]{3,20}$");

Accumulating validation errors in Java

validation regex error-accumulation
Beginner 9 steps
javascript
async function fetchAllPages(baseUrl, { pageSize = 100, headers = {} } = {}) {
  const results = [];
  let cursor = null;
 

Cursor-based pagination with fetch

pagination async-await fetch
Intermediate 6 steps
rust
use std::collections::HashMap;
 
pub fn word_frequencies(text: &str) -> HashMap<String, usize> {
    let mut counts: HashMap<String, usize> = HashMap::new();

Counting and ranking words in Rust

hashmap iterators sorting
Intermediate 7 steps
php
<?php
 
namespace App\Security;
 

A fixed-window rate limiter on APCu

rate-limiting fixed-window caching
Intermediate 8 steps
python
from flask import Blueprint, render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField

Handling a post form with a Flask Blueprint

blueprints form-validation post-redirect-get
Intermediate 7 steps
go
package storage
 
import (
	"bufio"

Streaming file downloads safely in Go

http streaming path-traversal
Intermediate 7 steps
typescript
type SearchResult = {
  id: string;
  title: string;
};

Cancelling stale searches with AbortController

abortcontroller cancellation async
Intermediate 7 steps
java
public class WorkPipeline {
    private final BlockingQueue<Task> queue = new LinkedBlockingQueue<>(1000);
    private static final Task POISON = new Task(-1, null);
    private final ExecutorService consumers = Executors.newFixedThreadPool(4);

A producer-consumer pipeline in Java

concurrency producer-consumer blocking-queue
Intermediate 8 steps
ruby
class OrderConfirmationJob < ApplicationJob
  queue_as :mailers
 
  retry_on Net::OpenTimeout, wait: :polynomially_longer, attempts: 5

Resilient background jobs in Rails

background-jobs retries idempotency
Intermediate 8 steps
javascript
import { useCallback, useEffect, useRef, useState } from 'react';
 
export function useInfiniteScroll(fetchPage) {
  const [items, setItems] = useState([]);

Building an infinite scroll hook in React

custom-hooks intersection-observer pagination
Advanced 6 steps
rust
use std::error::Error;
use std::fmt;
 
#[derive(Debug)]

Building a typed error enum in Rust

error-handling enums trait-implementation
Intermediate 9 steps
php
class PostController extends Controller
{
    public function index(Request $request)
    {

Eager loading without N+1 in Laravel

eager-loading n+1 query-builder
Intermediate 9 steps
python
import random
import time
import logging
from functools import wraps

A retry decorator with exponential backoff

decorators retry exponential-backoff
Intermediate 6 steps