Module: MicroStateMachine

Defined in:
lib/micro_state_machine.rb

Defined Under Namespace

Modules: ClassMethods Classes: InvalidState

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/micro_state_machine.rb', line 11

def self.included(klass)
  klass.class_attribute :_on_enter_state, :_on_exit_state, :_initial_state, :_after_state_change, :_states
  klass.send(:extend, ClassMethods)
  if klass.respond_to?(:after_initialize)
    klass.instance_eval do
      after_initialize(:set_initial_state)
    end
  end
end

Instance Method Details

#can_transition_to?(new_state) ⇒ Boolean

Returns:

  • (Boolean)


106
107
108
109
110
# File 'lib/micro_state_machine.rb', line 106

def can_transition_to?(new_state)
  states = self.class._states
  options = HashWithIndifferentAccess.new(states)[new_state]
  options.blank? || options[:from].include?(get_state)
end

#get_stateObject



91
92
93
# File 'lib/micro_state_machine.rb', line 91

def get_state
  send(state_column)
end

#is?(state) ⇒ Boolean

Returns:

  • (Boolean)


102
103
104
# File 'lib/micro_state_machine.rb', line 102

def is?(state)
  get_state.to_s == state.to_s
end

#set_initial_stateObject



95
96
97
98
99
100
# File 'lib/micro_state_machine.rb', line 95

def set_initial_state
  current_value = send(state_column)
  if current_value.nil?
    send("#{state_column}=", self.class._initial_state)
  end
end

#state_columnObject

Instance Methods



87
88
89
# File 'lib/micro_state_machine.rb', line 87

def state_column
  self.class.state_column
end

#transition_to(new_state) ⇒ Object

Raises:



112
113
114
115
116
117
118
119
120
121
# File 'lib/micro_state_machine.rb', line 112

def transition_to(new_state)
  old_state = get_state
  transition_method_name = "transition_from_#{old_state}_to_#{new_state}"
  raise InvalidState.new(old_state, new_state) unless respond_to?(transition_method_name)
  send(transition_method_name)
  self.class._after_state_change.each do |blk|
    instance_exec(old_state, new_state, &blk)
  end
  self
end