Class: EdgeStateMachine::Transition

Inherits:
Object
  • Object
show all
Defined in:
lib/edge-state-machine/transition.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(opts) ⇒ Transition

Returns a new instance of Transition.



5
6
7
# File 'lib/edge-state-machine/transition.rb', line 5

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

Instance Attribute Details

#fromObject (readonly)

Returns the value of attribute from.



3
4
5
# File 'lib/edge-state-machine/transition.rb', line 3

def from
  @from
end

#optionsObject (readonly)

Returns the value of attribute options.



3
4
5
# File 'lib/edge-state-machine/transition.rb', line 3

def options
  @options
end

#toObject (readonly)

Returns the value of attribute to.



3
4
5
# File 'lib/edge-state-machine/transition.rb', line 3

def to
  @to
end

Instance Method Details

#==(obj) ⇒ Object



40
41
42
# File 'lib/edge-state-machine/transition.rb', line 40

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

#execute(obj) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/edge-state-machine/transition.rb', line 27

def execute(obj)
  @on_transition.each do |transition|
    case transition
    when Symbol, String
      obj.send(transition)
    when Proc
      transition.call(obj)
    else
      raise ArgumentError, "You can only pass a Symbol, a String or a Proc to 'on_transition' - got #{transition.class}." unless transition.nil?
    end
  end
end

#find_next_state(obj) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
# File 'lib/edge-state-machine/transition.rb', line 9

def find_next_state(obj)
  # if we have many states we can go but no guard
  if @guard.nil? && @to.size > 1
    raise NoGuardFound.new("There are many possible 'to' states but there is no 'guard' to decide which state to go")
  end
  if @guard
    return execute_action(@guard, obj)
  else
    return @to.first
  end
end

#possible?(obj) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
# File 'lib/edge-state-machine/transition.rb', line 21

def possible?(obj)
  next_state = find_next_state(obj)
  return true if @to.include? next_state
  false
end