Class: TTY::Prompt::Timer

Inherits:
Object
  • Object
show all
Defined in:
lib/tty/prompt/timer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(duration, interval) ⇒ Timer

Returns a new instance of Timer.



12
13
14
15
16
17
18
# File 'lib/tty/prompt/timer.rb', line 12

def initialize(duration, interval)
  @duration = duration
  @interval = interval
  @total = 0.0
  @current = nil
  @events = []
end

Instance Attribute Details

#durationObject (readonly)

Returns the value of attribute duration.



6
7
8
# File 'lib/tty/prompt/timer.rb', line 6

def duration
  @duration
end

#intervalObject (readonly)

Returns the value of attribute interval.



10
11
12
# File 'lib/tty/prompt/timer.rb', line 10

def interval
  @interval
end

#totalObject (readonly)

Returns the value of attribute total.



8
9
10
# File 'lib/tty/prompt/timer.rb', line 8

def total
  @total
end

Instance Method Details

#on_tick(&block) ⇒ Object



36
37
38
# File 'lib/tty/prompt/timer.rb', line 36

def on_tick(&block)
  @events << block
end

#runtimeObject



32
33
34
# File 'lib/tty/prompt/timer.rb', line 32

def runtime
  time_now - @current
end

#startObject



20
21
22
23
24
# File 'lib/tty/prompt/timer.rb', line 20

def start
  return if @current

  @current = time_now
end

#stopObject



26
27
28
29
30
# File 'lib/tty/prompt/timer.rb', line 26

def stop
  return unless @current

  @current = nil
end

#time_nowObject

Object represeting current time



64
65
66
# File 'lib/tty/prompt/timer.rb', line 64

def time_now
  ::Process.clock_gettime(Process::CLOCK_MONOTONIC)
end

#while_remainingObject



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tty/prompt/timer.rb', line 40

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