class StateMachine::Event

An event defines an action that transitions an attribute from one state to another. The state that an attribute is transitioned to depends on the branches configured for the event.

Attributes

branches[R]

The list of branches that determine what state this event transitions objects to when fired

human_name[W]

The human-readable name for the event

known_states[R]

A list of all of the states known to this event using the configured branches/transitions as the source

machine[RW]

The state machine for which this event is defined

name[R]

The name of the event

qualified_name[R]

The fully-qualified name of the event, scoped by the machine's namespace

Public Instance Methods

can_fire?(object, requirements = {}) click to toggle source

Determines whether any transitions can be performed for this event based on the current state of the given object.

If the event can't be fired, then this will return false, otherwise true.

Note that this will not take the object context into account. Although a transition may be possible based on the state machine definition, object-specific behaviors (like validations) may prevent it from firing.

# File lib/state_machine/event.rb, line 125
def can_fire?(object, requirements = {})
  !transition_for(object, requirements).nil?
end
context(&block) click to toggle source

Evaluates the given block within the context of this event. This simply provides a DSL-like syntax for defining transitions.

# File lib/state_machine/event.rb, line 85
def context(&block)
  instance_eval(&block)
end
draw(graph, options = {}) click to toggle source

Draws a representation of this event on the given graph. This will create 1 or more edges on the graph for each branch (i.e. transition) configured.

Configuration options:

  • :human_name - Whether to use the event's human name for the node's label that gets drawn on the graph

# File lib/state_machine/event.rb, line 204
def draw(graph, options = {})
  valid_states = machine.states.by_priority.map {|state| state.name}
  branches.each do |branch|
    branch.draw(graph, options[:human_name] ? human_name : name, valid_states)
  end
  
  true
end
fire(object, *args) click to toggle source

Attempts to perform the next available transition on the given object. If no transitions can be made, then this will return false, otherwise true.

Any additional arguments are passed to the StateMachine::Transition#perform instance method.

# File lib/state_machine/event.rb, line 168
def fire(object, *args)
  machine.reset(object)
  
  if transition = transition_for(object)
    transition.perform(*args)
  else
    on_failure(object)
    false
  end
end
human_name(klass = @machine.owner_class) click to toggle source

Transforms the event name into a more human-readable format, such as “turn on” instead of “turn_on”

# File lib/state_machine/event.rb, line 79
def human_name(klass = @machine.owner_class)
  @human_name.is_a?(Proc) ? @human_name.call(self, klass) : @human_name
end
inspect() click to toggle source

Generates a nicely formatted description of this event's contents.

For example,

event = StateMachine::Event.new(machine, :park)
event.transition all - :idling => :parked, :idling => same
event   # => #<StateMachine::Event name=:park transitions=[all - :idling => :parked, :idling => same]>
# File lib/state_machine/event.rb, line 220
def inspect
  transitions = branches.map do |branch|
    branch.state_requirements.map do |state_requirement|
      "#{state_requirement[:from].description} => #{state_requirement[:to].description}"
    end * ', '
  end
  
  "#<#{self.class} name=#{name.inspect} transitions=[#{transitions * ', '}]>"
end
on_failure(object) click to toggle source

Marks the object as invalid and runs any failure callbacks associated with this event. This should get called anytime this event fails to transition.

# File lib/state_machine/event.rb, line 181
def on_failure(object)
  state = machine.states.match!(object)
  machine.invalidate(object, :state, :invalid_transition, [[:event, human_name(object.class)], [:state, state.human_name(object.class)]])
  
  Transition.new(object, machine, name, state.name, state.name).run_callbacks(:before => false)
end
reset() click to toggle source

Resets back to the initial state of the event, with no branches / known states associated. This allows you to redefine an event in situations where you either are re-using an existing state machine implementation or are subclassing machines.

# File lib/state_machine/event.rb, line 192
def reset
  @branches = []
  @known_states = []
end
transition(options) click to toggle source

Creates a new transition that determines what to change the current state to when this event fires.

Since this transition is being defined within an event context, you do not need to specify the :on option for the transition. For example:

state_machine do
  event :ignite do
    transition :parked => :idling, :idling => same, :if => :seatbelt_on? # Transitions to :idling if seatbelt is on
    transition all => :parked, :unless => :seatbelt_on?                  # Transitions to :parked if seatbelt is off
  end
end

See StateMachine::Machine#transition for a description of the possible configurations for defining transitions.

# File lib/state_machine/event.rb, line 105
def transition(options)
  raise ArgumentError, 'Must specify as least one transition requirement' if options.empty?
  
  # Only a certain subset of explicit options are allowed for transition
  # requirements
  assert_valid_keys(options, :from, :to, :except_from, :except_to, :if, :unless) if (options.keys - [:from, :to, :on, :except_from, :except_to, :except_on, :if, :unless]).empty?
  
  branches << branch = Branch.new(options.merge(:on => name))
  @known_states |= branch.known_states
  branch
end
transition_for(object, requirements = {}) click to toggle source

Finds and builds the next transition that can be performed on the given object. If no transitions can be made, then this will return nil.

Valid requirement options:

  • :from - One or more states being transitioned from. If none are specified, then this will be the object's current state.

  • :to - One or more states being transitioned to. If none are specified, then this will match any to state.

  • :guard - Whether to guard transitions with the if/unless conditionals defined for each one. Default is true.

# File lib/state_machine/event.rb, line 139
def transition_for(object, requirements = {})
  assert_valid_keys(requirements, :from, :to, :guard)
  requirements[:from] = machine.states.match!(object).name unless custom_from_state = requirements.include?(:from)
  
  branches.each do |branch|
    if match = branch.match(object, requirements)
      # Branch allows for the transition to occur
      from = requirements[:from]
      to = if match[:to].is_a?(LoopbackMatcher)
        from
      else
        values = requirements.include?(:to) ? [requirements[:to]].flatten : [from] | machine.states.keys(:name)
        match[:to].filter(values).first
      end
      
      return Transition.new(object, machine, name, from, to, !custom_from_state)
    end
  end
  
  # No transition matched
  nil
end

Protected Instance Methods

add_actions() click to toggle source

Add the various instance methods that can transition the object using the current event

# File lib/state_machine/event.rb, line 233
def add_actions
  # Checks whether the event can be fired on the current object
  machine.define_helper(:instance, "can_#{qualified_name}?") do |machine, object, *args|
    machine.event(name).can_fire?(object, *args)
  end
  
  # Gets the next transition that would be performed if the event were
  # fired now
  machine.define_helper(:instance, "#{qualified_name}_transition") do |machine, object, *args|
    machine.event(name).transition_for(object, *args)
  end
  
  # Fires the event
  machine.define_helper(:instance, qualified_name) do |machine, object, *args|
    machine.event(name).fire(object, *args)
  end
  
  # Fires the event, raising an exception if it fails
  machine.define_helper(:instance, "#{qualified_name}!") do |machine, object, *args|
    object.send(qualified_name, *args) || raise(StateMachine::InvalidTransition.new(object, machine, name))
  end
end