ruby
49 lines · 8 steps
A state machine for order transitions in Ruby
A frozen transition table drives valid order state changes, records history, and fires side effects on each move.
Explained by
highlit
1class Order
2 class InvalidTransition < StandardError; end
3
4 TRANSITIONS = {
5 pending: %i[paid cancelled],
6 paid: %i[shipped refunded],
7 shipped: %i[delivered],
8 delivered: %i[],
9 cancelled: %i[],
10 refunded: %i[]
11 }.freeze
12
13 attr_reader :state, :history
14
15 def initialize(state: :pending)
16 @state = state.to_sym
17 @history = []
18 end
19
20 def transition_to!(target)
21 target = target.to_sym
22 unless can_transition_to?(target)
23 raise InvalidTransition, "cannot move order from #{state} to #{target}"
24 end
25
26 @history << { from: state, to: target, at: Time.now }
27 @state = target
28 run_callback(target)
29 self
30 end
31
32 def can_transition_to?(target)
33 TRANSITIONS.fetch(state, []).include?(target.to_sym)
34 end
35
36 def final?
37 TRANSITIONS.fetch(state, []).empty?
38 end
39
40 private
41
42 def run_callback(target)
43 case target
44 when :paid then PaymentMailer.confirmation(self).deliver_later
45 when :shipped then ShipmentJob.perform_later(id: object_id)
46 when :refunded then RefundService.new(self).process!
47 end
48 end
49end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Encoding legal transitions as data keeps validation logic small and easy to audit.
- 2Raising a domain-specific error makes illegal transitions loud and self-documenting.
- 3Separating the guard, the state mutation, and the side effect keeps each concern testable.
Related explainers
ruby
class CreateOrderItems < ActiveRecord::Migration[7.1] def change create_table :order_items do |t| t.references :order, null: false, foreign_key: { on_delete: :cascade }
Enforcing order-item integrity in Rails
migrations
foreign-keys
validations
Intermediate
7 steps
python
import time import threading from enum import Enum from functools import wraps
Building a circuit breaker in Python
circuit-breaker
resilience
decorators
Advanced
7 steps
rust
use std::cmp::Ordering; use std::str::FromStr; #[derive(Debug, Clone, PartialEq, Eq)]
Parsing and ordering semantic versions in Rust
parsing
trait-implementation
ordering
Intermediate
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
ruby
class Registration < ApplicationRecord belongs_to :event validates :email, presence: true, format: { with: URI::MailTo::EMAIL_REGEXP }
Validating registrations in Rails
validations
i18n
error-handling
Intermediate
8 steps
ruby
class ApacheLogParser LINE_PATTERN = /\A(?<ip>\S+)\s\S+\s\S+\s\[(?<time>[^\]]+)\]\s"(?<method>[A-Z]+)\s(?<path>\S+)\s(?<protocol>[^"]+)"\s(?<status>\d{3})\s(?<bytes>\d+|-)/ TIME_FORMAT = "%d/%b/%Y:%H:%M:%S %z"
Parsing Apache logs with named captures
regex
named-captures
parsing
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-state-machine-for-order-transitions-in-ruby-explained-ruby-3c06/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.