Event support for Statesman.
gem install statesman-events
class TaskStateMachine
include Statesman::Machine
include Statesman::Events
state :unstarted, initial: true
state :started
state :finished
state :cancelled
event :start do
transition from: :unstarted, to: :started
end
event :finish do
transition from: :started, to: :finished
end
event :cancel do
transition from: :unstarted, to: :cancelled
transition from: :started, to: :cancelled
end
event :restart do
transition from: :finished, to: :started
transition from: :cancelled, to: :started
end
end
class Task < ActiveRecord::Base
delegate :current_state, :trigger, :available_events, to: :state_machine
def state_machine
@state_machine ||= TaskStateMachine.new(self)
end
end
task = Task.new
task.current_state # => "unstarted"
task.trigger(:start) # => true/false
task.current_state # => "started"
task.available_events # => [:finish, :cancel]
ExampleMachine.event(:some_event) do
transition from: :some_state, to: :another_state
transition from: :some_other_state, to: :yet_another_state
end
Define an event rule. When triggered, the first available transition from the current state will be called.
instance.trigger(:some_event)
Triggers the passed event, returning true
on success. Returns false on
failure.
instance.trigger!(:some_event)
Triggers the passed event, returning true
on success. Raises
Statesman::GuardFailedError
or Statesman::InvalidTransitionError
on failure.
instance.available_events
Returns an array of events you can trigger
from the current state.