module MicroStateMachine::ClassMethods

Public Instance Methods

after_state_change(*args, &block) click to toggle source
# File lib/micro_state_machine.rb, line 80
def after_state_change(*args, &block)
  _after_state_change.push block
end
on_enter_state(state, &block) click to toggle source
# File lib/micro_state_machine.rb, line 66
def on_enter_state(state, &block)
  h = _on_enter_state
  h[state] ||= []
  h[state].push block
  self._on_enter_state = h
end
on_exit_state(state, &block) click to toggle source
# File lib/micro_state_machine.rb, line 73
def on_exit_state(state, &block)
  h = _on_exit_state
  h[state] ||= []
  h[state].push block
  self._on_exit_state = h
end
state(state, options = {}) click to toggle source

used to define the possible states the “machine” could be in. defines convenience {state}! and {state}? methods worth noting that transition_from_{from_state}to{state} could be used to implement guards.

# File lib/micro_state_machine.rb, line 30
def state(state, options = {})
  self._initial_state ||= state
  self._after_state_change ||= []
  self._on_enter_state ||= HashWithIndifferentAccess.new
  self._on_exit_state ||= HashWithIndifferentAccess.new
  self._states ||= {}
  _states[state] = options
  from = options[:from] || _states.keys

  from.each do |from_state|
    define_method("#{state}!") do
      transition_to(state)
    end

    define_method("#{state}?") do
      is?(state)
    end

    define_method("transition_from_#{from_state}_to_#{state}") do
      on_exit_state = self.class._on_exit_state
      on_enter_state = self.class._on_enter_state
      if on_exit_state[from_state]
        on_exit_state[from_state].each do |blk|
          instance_eval &blk
        end
      end
      send("#{state_column}=", state)
      if on_enter_state[state]
        on_enter_state[state].each do |blk|
          instance_eval &blk
        end
      end
    end
  end
end
state_column() click to toggle source

override this to change the default state column name

# File lib/micro_state_machine.rb, line 23
def state_column
  'state'
end