51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
|
# File 'lib/state_boss.rb', line 51
def state_machine(&block)
class_eval do
block.call
end
raise StateInitializationError, 'state is uninitialized.' if @default_state.nil?
@transitions.keys.each do |key|
define_method("#{key}?") do
_state == key
end
end
@events.keys.each do |key|
define_method(key) do
raise InvalidTransitionError, 'state transition finished.' if finished_state?
events = self.class.instance_variable_get(:@events)
to = events[key][:to]
transitions = self.class.instance_variable_get(:@transitions)
unless transitions[_state][:to].include?(to)
raise InvalidTransitionError, "can't change state from #{current_state} to #{to}"
end
before_state = _state
@_state = to
begin
callback = events[key][:callback]
result = callback.call(self) if !callback.nil?
record_event(before_state, key)
result
rescue => e
@_state = before_state
raise e
end
end
end
end
|