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
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 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.