Module: Ext::StateMachine

Defined in:
app/models/com/ext/state_machine.rb

Instance Method Summary collapse

Instance Method Details

#next_state(state_name, &block) ⇒ Object



54
55
56
# File 'app/models/com/ext/state_machine.rb', line 54

def next_state(state_name, &block)
  next_states(state_name, &block).first
end

#next_states(state_name, &block) ⇒ Object

obj.next_states(:state) do |result|

result.reject

end



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'app/models/com/ext/state_machine.rb', line 61

def next_states(state_name, &block)
  _states = self.class.send(state_name.to_s.pluralize)
  _states = _states.keys
  _state = self.send(state_name)

  if _state.nil?
    next_index = 0
  else
    i = _states.index(_state)
    next_index = i + 1
  end
  result = _states[next_index..(_states.size - 1)]

  if block_given?
    yield block.call(result)
  else
    result
  end
end

#next_to(options = {}, &block) ⇒ Object

obj.next_to state: ‘xxx’



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'app/models/com/ext/state_machine.rb', line 8

def next_to(options = {}, &block)
  options.each do |column, value|
    if self.class.method_defined? "next_#{column}_states"
      _next_state = self.send("next_#{column}_states").first
    else
      _next_state = next_state(column, &block)
    end

    if _next_state == value.to_s
      assign_attributes(column => value)
    else
      error_msg = "Next state is wrong, should be #{_next_state}"
      errors.add column, error_msg
      raise ActiveRecord::Rollback, error_msg
    end
  end
end

#next_to!(options = {}, &block) ⇒ Object



26
27
28
29
# File 'app/models/com/ext/state_machine.rb', line 26

def next_to!(options = {}, &block)
  self.next_to(options, &block)
  self.save!
end

#trigger_to(options = {}, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/models/com/ext/state_machine.rb', line 31

def trigger_to(options = {}, &block)
  options.each do |column, value|
    if self.class.method_defined? "next_#{column}_states"
      _next_states = self.send "next_#{column}_states"
    else
      _next_states = next_states(column, &block)
    end

    if _next_states.include?(value.to_s)
      assign_attributes(column => value)
    else
      error_msg = "Next state is wrong, should be one of #{_next_states.join(', ')}"
      errors.add column, error_msg
      raise ActiveRecord::Rollback, error_msg
    end
  end
end

#trigger_to!(options = {}, &block) ⇒ Object



49
50
51
52
# File 'app/models/com/ext/state_machine.rb', line 49

def trigger_to!(options = {}, &block)
  self.trigger_to(options, &block)
  self.save!
end