Module: StateMachine
- Defined in:
- app/models/concerns/state_machine.rb
Instance Method Summary collapse
- #next_state(state_name, &block) ⇒ Object
-
#next_states(state_name, &block) ⇒ Object
obj.next_states(:state) do |result| result.reject end.
-
#next_to(options = {}, &block) ⇒ Object
obj.next_to state: ‘xxx’.
- #next_to!(options = {}, &block) ⇒ Object
- #trigger_to(options = {}, &block) ⇒ Object
- #trigger_to!(options = {}, &block) ⇒ Object
Instance Method Details
#next_state(state_name, &block) ⇒ Object
52 53 54 |
# File 'app/models/concerns/state_machine.rb', line 52 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
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
# File 'app/models/concerns/state_machine.rb', line 59 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’
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'app/models/concerns/state_machine.rb', line 6 def next_to( = {}, &block) .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
24 25 26 27 |
# File 'app/models/concerns/state_machine.rb', line 24 def next_to!( = {}, &block) self.next_to(, &block) self.save! end |
#trigger_to(options = {}, &block) ⇒ Object
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'app/models/concerns/state_machine.rb', line 29 def trigger_to( = {}, &block) .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
47 48 49 50 |
# File 'app/models/concerns/state_machine.rb', line 47 def trigger_to!( = {}, &block) self.trigger_to(, &block) self.save! end |