Class: Chamomile::Stopwatch

Inherits:
Object
  • Object
show all
Defined in:
lib/chamomile/components/stopwatch.rb

Overview

Count-up stopwatch with start/stop/reset and tick-based updates.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(interval: 1.0) ⇒ Stopwatch

Returns a new instance of Stopwatch.



26
27
28
29
30
31
32
# File 'lib/chamomile/components/stopwatch.rb', line 26

def initialize(interval: 1.0)
  @id = self.class.next_id
  @interval = interval
  @elapsed = 0.0
  @tag = 0
  @running = false
end

Instance Attribute Details

#elapsedObject (readonly)

Returns the value of attribute elapsed.



24
25
26
# File 'lib/chamomile/components/stopwatch.rb', line 24

def elapsed
  @elapsed
end

#idObject (readonly)

Returns the value of attribute id.



24
25
26
# File 'lib/chamomile/components/stopwatch.rb', line 24

def id
  @id
end

#intervalObject (readonly)

Returns the value of attribute interval.



24
25
26
# File 'lib/chamomile/components/stopwatch.rb', line 24

def interval
  @interval
end

Class Method Details

.next_idObject



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/chamomile/components/stopwatch.rb', line 12

def self.next_id
  @id_mutex.synchronize do
    if Process.pid != @id_pid
      @id_pid = Process.pid
      @next_id = 0
      @id_mutex = Mutex.new
    end
    @next_id += 1
    "#{@id_pid}-sw-#{@next_id}"
  end
end

Instance Method Details

#handle(msg) ⇒ Object Also known as: update



67
68
69
70
71
72
73
74
# File 'lib/chamomile/components/stopwatch.rb', line 67

def handle(msg)
  return unless msg.is_a?(StopwatchTickMsg)
  return unless msg.id == @id && msg.tag == @tag

  @elapsed += @interval
  @tag += 1
  tick_cmd
end

#resetObject



56
57
58
59
60
61
# File 'lib/chamomile/components/stopwatch.rb', line 56

def reset
  @elapsed = 0.0
  @running = false
  @tag += 1
  self
end

#running?Boolean

Returns:

  • (Boolean)


63
64
65
# File 'lib/chamomile/components/stopwatch.rb', line 63

def running?
  @running
end

#start_cmdObject



34
35
36
37
38
39
# File 'lib/chamomile/components/stopwatch.rb', line 34

def start_cmd
  return nil if @running

  @running = true
  tick_cmd
end

#stopObject



41
42
43
44
45
# File 'lib/chamomile/components/stopwatch.rb', line 41

def stop
  @running = false
  @tag += 1
  self
end

#toggleObject



47
48
49
50
51
52
53
54
# File 'lib/chamomile/components/stopwatch.rb', line 47

def toggle
  if @running
    stop
    nil
  else
    start_cmd
  end
end

#viewObject



78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/chamomile/components/stopwatch.rb', line 78

def view
  total = @elapsed.ceil.to_i
  hours = total / 3600
  minutes = (total % 3600) / 60
  seconds = total % 60

  if hours.positive?
    format("%d:%02d:%02d", hours, minutes, seconds)
  else
    format("%02d:%02d", minutes, seconds)
  end
end