module EnumStateMachine
Overview
Define type-safe finite state machine for Crystal where the states are defined using enum's.
enum Health
Alive
Dead
Zombie
end
class Player
include EnumStateMachine
getter hp = 100
state_machine(Health, initial: Health::Alive) do
event :die, to: Health::Dead
event :resurrect, from: Health::Dead, to: Health::Alive, guard: ->{ hp <= 0 }
event :succumb, except_from: Health::Alive, to: Health::Zombie
end
end
Defined in:
enum_state_machine.crMacro Summary
-
state_machine(state_enum, *, initial, &block)
Setup a state machine based on state_enum enumeration, with initial value, and block containing the
event
declarations.
Macro Detail
macro state_machine(state_enum, *, initial, &block)
#
Setup a state machine based on state_enum enumeration, with initial value, and block containing the
event
declarations.
Example:, given
enum Health
with valuesAlive
andDead
, astate_machine
declared with an event:die
that transitions toDead
makes the following methods available:
heath
to get the current statedead?
to check if state isDead
alive?
to check if state isAlive
die
to make the transition if possiblemay_die?
to check if player candie
Using different enum
types, multiple state machines can be setup in the same object.