class Chamomile::Timer
Countdown timer with timeout notification and tick-based updates.
Attributes
Public Class Methods
Source
# File lib/chamomile/components/timer.rb, line 27 def initialize(timeout:, interval: 1.0) @id = self.class.next_id @timeout = timeout.to_f @interval = interval @remaining = @timeout @tag = 0 @running = false end
Source
# File lib/chamomile/components/timer.rb, line 13 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}-tm-#{@next_id}" end end
Public Instance Methods
Source
# File lib/chamomile/components/timer.rb, line 73 def handle(msg) case msg when TimerTickMsg return unless msg.id == @id && msg.tag == @tag @remaining = [(@remaining - @interval), 0.0].max @tag += 1 if @remaining <= 0 @running = false timeout_cmd else tick_cmd end end end
Also aliased as: update
Source
# File lib/chamomile/components/timer.rb, line 58 def reset @remaining = @timeout @running = false @tag += 1 self end
Source
# File lib/chamomile/components/timer.rb, line 36 def start_cmd return nil if @running || timed_out? @running = true tick_cmd end
Source
# File lib/chamomile/components/timer.rb, line 43 def stop @running = false @tag += 1 self end
Source
# File lib/chamomile/components/timer.rb, line 69 def timed_out? @remaining <= 0 end
Source
# File lib/chamomile/components/timer.rb, line 49 def toggle if @running stop nil else start_cmd end end
Source
# File lib/chamomile/components/timer.rb, line 92 def view total = @remaining.ceil.to_i total = 0 if total.negative? 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