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.cr

Macro Summary

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 values Alive and Dead, a state_machine declared with an event :die that transitions to Dead makes the following methods available:

  • heath to get the current state
  • dead? to check if state is Dead
  • alive? to check if state is Alive
  • die to make the transition if possible
  • may_die? to check if player can die

Using different enum types, multiple state machines can be setup in the same object.


[View source]