Sha256: f01997de215059b44601c6b81229f87c31d25f7c5ed215728286fbba636466bd

Contents?: true

Size: 1.24 KB

Versions: 1

Compression:

Stored size: 1.24 KB

Contents

module EdgeStateMachine
  class StateTransition
    attr_reader :from, :to, :options

    def initialize(opts)
      @from, @to, @guard, @on_transition = opts[:from], opts[:to], opts[:guard], opts[:on_transition]
      @options = opts
    end

    def perform(obj)
      case @guard
      when Symbol, String
        obj.send(@guard)
      when Proc
        @guard.call(obj)
      else
        true
      end
    end

    def execute(obj, *args)
      case @on_transition
      when Symbol, String
        obj.send(@on_transition, *args)
      when Proc
        @on_transition.call(obj, *args)
      when Array
        @on_transition.each do |callback|
          # Yes, we're passing always the same parameters for each callback in here.
          # We should probably drop args altogether in case we get an array.
          obj.send(callback, *args)
        end
      else
        # TODO We probably should check for this in the constructor and not that late.
        raise ArgumentError, "You can only pass a Symbol, a String, a Proc or an Array to 'on_transition' - got #{@on_transition.class}." unless @on_transition.nil?
      end
    end

    def ==(obj)
      @from == obj.from && @to == obj.to
    end

    def from?(value)
      @from == value
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
edge-state-machine-0.0.1 lib/edge-state-machine/state_transition.rb