Sha256: 207e4129ef3eacb8dc76ba472eaf88f65201d346184cbc6652994c51d69e8dc7

Contents?: true

Size: 1.05 KB

Versions: 4

Compression:

Stored size: 1.05 KB

Contents

module Stateflow
  class NoTransitionFound < Exception; end
  class NoStateFound < Exception; end
  
  class Event
    attr_accessor :name, :transitions
    
    def initialize(name, &transitions)
      @name = name
      @transitions = Array.new
      
      instance_eval(&transitions)
    end
    
    def fire(current_state, klass)
      transition = @transitions.select{ |t| t.from.include? current_state.name }.first
      raise NoTransitionFound.new("No transition found for event #{@name}") if transition.nil?
      
      return false unless transition.can_transition?(klass)
      
      new_state = klass.machine.states[transition.find_to_state(klass)]
      raise NoStateFound.new("Invalid state #{transition.to.to_s} for transition.") if new_state.nil?
      
      current_state.execute_action(:exit, klass)
      klass.current_state = new_state
      new_state.execute_action(:enter, klass)
      true
    end
    
    private
    def transitions(args = {})
      transition = Stateflow::Transition.new(args)
      @transitions << transition
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
stateflow-0.0.4 lib/stateflow/event.rb
stateflow-0.0.3 lib/stateflow/event.rb
stateflow-0.0.2 lib/stateflow/event.rb
stateflow-0.0.1 lib/stateflow/event.rb