Module: MicroStateMachine::ClassMethods

Defined in:
lib/micro_state_machine.rb

Instance Method Summary collapse

Instance Method Details

#after_state_change(*args, &block) ⇒ Object



80
81
82
# 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) ⇒ Object



66
67
68
69
70
71
# 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) ⇒ Object



73
74
75
76
77
78
# 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 = {}) ⇒ Object

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



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# 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_columnObject

override this to change the default state column name



23
24
25
# File 'lib/micro_state_machine.rb', line 23

def state_column
  'state'
end