1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
|
# frozen_string_literal: true
module TTY
class Prompt
class Timer
attr_reader :duration
attr_reader :total
attr_reader :interval
def initialize(duration, interval)
@duration = duration
@interval = interval
@total = 0.0
@current = nil
@events = []
end
def start
return if @current
@current = time_now
end
def stop
return unless @current
@current = nil
end
def runtime
time_now - @current
end
def on_tick(&block)
@events << block
end
def while_remaining
start
remaining = duration
if @duration
while remaining >= 0.0
if runtime >= total
tick = duration - @total
@events.each { |block| block.(tick) }
@total += @interval
end
yield(remaining)
remaining = duration - runtime
end
else
loop { yield }
end
ensure
stop
end
if defined?(Process::CLOCK_MONOTONIC)
# Object representing current time
def time_now
::Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
else
# Object represeting current time
def time_now
::Time.now
end
end
end # Timer
end # Prompt
end # TTY
|