Class: MicroFSM

Inherits:
Object
  • Object
show all
Defined in:
lib/microfsm.rb,
lib/microfsm/version.rb

Constant Summary collapse

InvalidEvent =
Class.new(NoMethodError)
InvalidState =
Class.new(ArgumentError)
InvalidTransition =
Class.new(ArgumentError)
VERSION =

2026-04-20

"1.0.0"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) ⇒ MicroFSM

Returns a new instance of MicroFSM.



13
14
15
16
17
18
# File 'lib/microfsm.rb', line 13

def initialize(initial_state)
  @state = initial_state
  @timed = false
  @transitions_for = {}
  @callback_for = {}
end

Instance Attribute Details

#current_utcObject

Returns the value of attribute current_utc.



11
12
13
# File 'lib/microfsm.rb', line 11

def current_utc
  @current_utc
end

#previous_utcObject

Returns the value of attribute previous_utc.



10
11
12
# File 'lib/microfsm.rb', line 10

def previous_utc
  @previous_utc
end

#stateObject

Returns the value of attribute state.



8
9
10
# File 'lib/microfsm.rb', line 8

def state
  @state
end

#timedObject

Returns the value of attribute timed.



9
10
11
# File 'lib/microfsm.rb', line 9

def timed
  @timed
end

Instance Method Details

#eventsObject



56
57
58
# File 'lib/microfsm.rb', line 56

def events
  @transitions_for.keys.sort
end

#statesObject



64
65
66
# File 'lib/microfsm.rb', line 64

def states
  @transitions_for.values.map(&:to_a).flatten.uniq.sort
end

#trigger(event) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/microfsm.rb', line 36

def trigger(event)
  if @timed
    @previous_utc = @current_utc
    @current_utc = Time.now.utc
  end

  trigger?(event) and transit(event)
end

#trigger!(event) ⇒ Object



45
46
47
48
# File 'lib/microfsm.rb', line 45

def trigger!(event)
  trigger(event) or
    raise InvalidState.new(msg(event))
end

#trigger?(event) ⇒ Boolean

Returns:

  • (Boolean)

Raises:



50
51
52
53
54
# File 'lib/microfsm.rb', line 50

def trigger?(event)
  raise InvalidEvent.new(msg(event)) unless @transitions_for.has_key?(event)

  @transitions_for[event].has_key?(state)
end

#triggerable_eventsObject



60
61
62
# File 'lib/microfsm.rb', line 60

def triggerable_events
  events.select { |event| trigger?(event) }.sort
end

#when(event, transitions, &block) ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/microfsm.rb', line 20

def when(event, transitions, &block)
  @transitions_for[event] ||= {}
  @callback_for[event] ||= {}
  @timed = true if block

  transitions.each do |from, to|
    nto = @transitions_for[event][from]
    raise InvalidTransition if nto && nto != to

    @transitions_for[event][from] = to
    @callback_for[event][from] = block if block
    @current_utc = Time.now.utc if block
  end
  self
end