Class: Fsm::Machine

Inherits:
Object
  • Object
show all
Defined in:
lib/fsm/machine.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(schema:, changeset:) ⇒ Machine

Returns a new instance of Machine.

Raises:

  • (ArgumentError)


5
6
7
8
9
10
# File 'lib/fsm/machine.rb', line 5

def initialize(schema:, changeset:)
  raise ArgumentError.new("changeset argument must be an array with only 2 elements") unless (changeset.is_a?(Array) && changeset.length == 2)
  raise ArgumentError.new("schema is invalid") unless valid_schema?(schema)
  @schema    = schema
  @from, @to = changeset
end

Instance Attribute Details

#errorObject

Returns the value of attribute error.



3
4
5
# File 'lib/fsm/machine.rb', line 3

def error
  @error
end

#fromObject

Returns the value of attribute from.



3
4
5
# File 'lib/fsm/machine.rb', line 3

def from
  @from
end

#schemaObject

Returns the value of attribute schema.



3
4
5
# File 'lib/fsm/machine.rb', line 3

def schema
  @schema
end

#toObject

Returns the value of attribute to.



3
4
5
# File 'lib/fsm/machine.rb', line 3

def to
  @to
end

Instance Method Details

#transitionObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/fsm/machine.rb', line 12

def transition
  found_transition = schema.dup.select do |mapping|
    mapping[:from].include?(from.to_sym) && mapping[:to] == to.to_sym
  end

  if found_transition.length > 1
    @error = TransitionError.new(self)
    @error.message = "Found an ambiguous number of transitions that can ocurr: #{found_transition.map { |x| x[:call] }}"
    false
  elsif found_transition.length < 1
    @error = TransitionError.new(self)
    @error.message = "Could not find a transition from #{from} to #{to}"
    false
  else
    found_transition.pop[:call]
  end
end

#transition!Object



30
31
32
# File 'lib/fsm/machine.rb', line 30

def transition!
  transition || raise(error)
end

#valid_schema?(schema) ⇒ Boolean

Returns:

  • (Boolean)


34
35
36
37
38
39
40
41
42
# File 'lib/fsm/machine.rb', line 34

def valid_schema?(schema)
  return false unless schema.is_a?(Array)
  schema.all? do |mapping|
    mapping.keys == [:from, :to, :call] &&
    mapping[:from].is_a?(Array) &&
    mapping[:to].is_a?(Symbol) &&
    mapping[:call].is_a?(Symbol)
  end
end