Sha256: 603d69f1efadee18cb9bbce24ca8d378b2ce4e39a058952dea9e8224bea3963f

Contents?: true

Size: 954 Bytes

Versions: 2

Compression:

Stored size: 954 Bytes

Contents

module Stateflow
  class IncorrectTransition < Exception; end
  
  class Transition
    attr_reader :from, :to, :if, :decide
    
    def initialize(args)
      @from = [args[:from]].flatten
      @to = args[:to]
      @if = args[:if]
      @decide = args[:decide]
    end 
    
    def can_transition?(base)
      return true unless @if
      execute_action(@if, base)
    end
    
    def find_to_state(base)
      raise IncorrectTransition.new("Array of destinations and no decision") if @to.is_a?(Array) && @decide.nil?
      return @to unless @to.is_a?(Array)
      
      to = execute_action(@decide, base)
      
      raise NoStateFound.new("Decision did not return a state that was set in the 'to' argument") unless @to.include?(to)
      to
    end
      
    private
    def execute_action(action, base)
      case action
      when Symbol, String
        base.send(action)
      when Proc
        action.call(base)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
stateflow-0.5.0.beta lib/stateflow/transition.rb
stateflow-0.4.2 lib/stateflow/transition.rb