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

Walkthrough

Space play step click any line
Three takeaways
  1. 1Encoding legal transitions as data keeps validation logic small and easy to audit.
  2. 2Raising a domain-specific error makes illegal transitions loud and self-documenting.
  3. 3Separating the guard, the state mutation, and the side effect keeps each concern testable.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A state machine for order transitions in Ruby — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code