-
Notifications
You must be signed in to change notification settings - Fork 105
/
state.rb
52 lines (45 loc) · 1.04 KB
/
state.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#This pattern try to simplify complicate control flows changing an object's behaviour dynamically
class Operation
attr_reader :state
def initialize
@state = OperationOpenState.new
end
def trigger(state)
@state = @state.next(state)
end
end
class OperationOpenState
def next(state)
if valid?(state)
OperationPendingPaymentState.new
else
raise IllegalStateJumpError
end
end
def valid?(state)
state == :pending_payment
end
end
class OperationPendingPaymentState
def next(state)
OperationConfirmState.new if valid?(state)
end
def valid?(state)
state == :confirm
end
end
class IllegalStateJumpError < StandardError; end
class OperationConfirmState; end
#Usage
operation = Operation.new
puts operation.state.class
#=> OperationOpenState
operation.trigger :pending_payment
puts operation.state.class
#=> OperationPendingPaymentState
operation.trigger :confirm
puts operation.state.class
#=> OperationConfirmState
operation = Operation.new
operation.trigger :confirm
#=> raise IllegalStateJumpError