Sha256: de5d3cc02ad355fa33324d8154114c2296dcb960f094f1264948d51d83188573

Contents?: true

Size: 1.39 KB

Versions: 15

Compression:

Stored size: 1.39 KB

Contents

# 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

Version data entries

15 entries across 15 versions & 3 rubygems

Version Path
tty-prompt-0.23.1 lib/tty/prompt/timer.rb
tty-prompt-0.23.0 lib/tty/prompt/timer.rb
lotrd-0.1.9 vendor/cache/ruby/2.6.0/gems/tty-prompt-0.22.0/lib/tty/prompt/timer.rb
lotrd-0.1.8 vendor/cache/ruby/2.6.0/gems/tty-prompt-0.22.0/lib/tty/prompt/timer.rb
lotrd-0.1.6 vendor/cache/ruby/2.6.0/gems/tty-prompt-0.22.0/lib/tty/prompt/timer.rb
lotrd-0.1.5 vendor/cache/ruby/2.6.0/gems/tty-prompt-0.22.0/lib/tty/prompt/timer.rb
tty-prompt-0.22.0 lib/tty/prompt/timer.rb
pokedex-terminal-0.2.8 vendor/bundle/ruby/2.7.0/gems/tty-prompt-0.21.0/lib/tty/prompt/timer.rb
pokedex-terminal-0.2.7 vendor/bundle/ruby/2.7.0/gems/tty-prompt-0.21.0/lib/tty/prompt/timer.rb
pokedex-terminal-0.2.6 vendor/bundle/ruby/2.7.0/gems/tty-prompt-0.21.0/lib/tty/prompt/timer.rb
pokedex-terminal-0.2.5 vendor/bundle/ruby/2.7.0/gems/tty-prompt-0.21.0/lib/tty/prompt/timer.rb
pokedex-terminal-0.2.4 vendor/bundle/ruby/2.7.0/gems/tty-prompt-0.21.0/lib/tty/prompt/timer.rb
tty-prompt-0.21.0 lib/tty/prompt/timer.rb
tty-prompt-0.20.0 lib/tty/prompt/timer.rb
tty-prompt-0.19.0 lib/tty/prompt/timer.rb