class FiniteMachine::Transition
Class describing a transition associated with a given event
The {Transition} is created with the `event` helper.
@example Converting event into {Transition}
event :go, :red => :green will be translated to Transition.new(context, :go, {states: {:red => :green}})
@api private
Public Class Methods
new(context, name, attrs = {})
click to toggle source
Initialize a Transition
@example
attributes = {states: {green: :yellow}} Transition.new(context, :go, attributes)
@param [Object] context
the context this transition evaluets conditions in
@param [Hash] attrs
@return [Transition]
@api public
# File lib/finite_machine/transition.rb, line 48 def initialize(context, name, attrs = {}) @context = context @name = name @states = attrs.fetch(:states, {}) @if = Array(attrs.fetch(:if, [])) @unless = Array(attrs.fetch(:unless, [])) @conditions = make_conditions freeze end
Public Instance Methods
check_conditions(*args)
click to toggle source
Verify conditions returning true if all match, false otherwise
@param [Array] args
the arguments for the condition
@return [Boolean]
@api private
# File lib/finite_machine/transition.rb, line 76 def check_conditions(*args) conditions.all? do |condition| condition.call(context, *args) end end
inspect()
click to toggle source
Return string representation
@return [String]
@api public
# File lib/finite_machine/transition.rb, line 134 def inspect transitions = @states.map { |from, to| "#{from} -> #{to}" }.join(", ") "<##{self.class} @name=#{@name}, @transitions=#{transitions}, " \ "@when=#{@conditions}>" end
make_conditions()
click to toggle source
Reduce conditions
@return [Array]
@api private
# File lib/finite_machine/transition.rb, line 63 def make_conditions @if.map { |c| Callable.new(c) } + @unless.map { |c| Callable.new(c).invert } end
matches?(from)
click to toggle source
Check if this transition matches from state
@param [Symbol] from
the from state to match against
@example
transition = Transition.new(context, states: {:green => :red}) transition.matches?(:green) # => true
@return [Boolean]
Return true if match is found, false otherwise.
@api public
# File lib/finite_machine/transition.rb, line 95 def matches?(from) states.keys.any? { |state| [ANY_STATE, from].include?(state) } end
to_s()
click to toggle source
Return transition name
@example
transition = Transition.new(context, name: :go) transition.to_s # => "go"
@return [String]
@api public
# File lib/finite_machine/transition.rb, line 125 def to_s @name.to_s end
to_state(from)
click to toggle source
Find to state for this transition given the from state
@param [Symbol] from
the from state to check
@example
transition = Transition.new(context, states: {:green => :red}) transition.to_state(:green) # => :red
@return [Symbol]
the to state
@api public
# File lib/finite_machine/transition.rb, line 112 def to_state(from) states[from] || states[ANY_STATE] end