Sha256: cc7cd4b3d343523267f093684e49ed089ac3d255c6b492771d2b376c31e42a07

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

module CliSpinnable
  class Writer
    class Error < CliSpinnableError; end

    REFRESH_DELAY_IN_SECONDS = 0.1

    def initialize(output, line)
      @output = output
      @line = line
      @queue = Queue.new
      @session = start_session
    end

    def print(str)
      push(:sign=, :spin)
      push(:<<, str)
      self
    end

    def tick
      push(:sign=, :tick)
      push(:newline=, true)
      push(:str=, '')
      self
    end

    def failure
      push(:sign=, :fail)
      push(:newline=, true)
      self
    end

    def finalize
      push(:sign=, :blank)
      push(:str=, '')
      finalize_session
      self
    end

    private

    attr_reader :output, :line, :queue, :session

    def push(attr, val)
      raise Error, 'Session finalized' unless session.status
      queue.push([attr, val])
    end

    def start_session
      Thread.new do
        loop do
          loop do
            output.write reload_line.to_s_resetting_newline
            break if queue.empty?
          end
          break if Thread.current[:finalize]
          sleep REFRESH_DELAY_IN_SECONDS
        end
      end
    end

    def reload_line
      line.public_send(*queue.pop) unless queue.empty?
      line
    end

    def finalize_session
      session[:finalize] = true
      session.join
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cli_spinnable-0.1 lib/cli_spinnable/writer.rb