Class: Philiprehberger::StateMachine::Statistics

Inherits:
Object
  • Object
show all
Defined in:
lib/philiprehberger/state_machine/statistics.rb

Overview

Tracks transition counts and time spent in each state.

Instance Method Summary collapse

Constructor Details

#initialize(initial_state) ⇒ Statistics

Returns a new instance of Statistics.

Parameters:

  • initial_state (Symbol)


8
9
10
11
12
13
14
# File 'lib/philiprehberger/state_machine/statistics.rb', line 8

def initialize(initial_state)
  @transition_counts = Hash.new(0)
  @state_enter_times = { initial_state => Time.now }
  @time_in_states = Hash.new(0.0)
  @current_state = initial_state
  @total_transitions = 0
end

Instance Method Details

#record_transition(from, to) ⇒ Object

Record a transition from one state to another.

Parameters:

  • from (Symbol)
  • to (Symbol)


20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/philiprehberger/state_machine/statistics.rb', line 20

def record_transition(from, to)
  now = Time.now
  key = :"#{from}_to_#{to}"
  @transition_counts[key] += 1
  @total_transitions += 1

  if @state_enter_times[from]
    @time_in_states[from] += now - @state_enter_times[from]
  end

  @state_enter_times[to] = now
  @current_state = to
end

#time_in_state(state) ⇒ Float

Time spent in a specific state (in seconds). If currently in that state, includes elapsed time.

Parameters:

  • state (Symbol)

Returns:

  • (Float)


46
47
48
49
50
51
52
# File 'lib/philiprehberger/state_machine/statistics.rb', line 46

def time_in_state(state)
  total = @time_in_states[state]
  if @current_state == state && @state_enter_times[state]
    total += Time.now - @state_enter_times[state]
  end
  total
end

#to_hHash

Return full statistics as a hash.

Returns:

  • (Hash)


57
58
59
60
61
62
63
# File 'lib/philiprehberger/state_machine/statistics.rb', line 57

def to_h
  {
    total_transitions: @total_transitions,
    transition_counts: @transition_counts.dup,
    time_in_states: all_time_in_states
  }
end

#transition_countInteger

Total number of transitions.

Returns:

  • (Integer)


37
38
39
# File 'lib/philiprehberger/state_machine/statistics.rb', line 37

def transition_count
  @total_transitions
end