Sha256: dd0524ca6f57b0b88d99b86175445ed155a63d1f83d7d417751a79779900cf3d

Contents?: true

Size: 1.27 KB

Versions: 24

Compression:

Stored size: 1.27 KB

Contents

module Potassium
  # TODO: I don't know if this is a concern of this gem. Maybe we should move this later
  class TextSpinner
    attr_accessor :wait_condition, :base_message, :interval, :message_continuations,
      :counter, :started

    DEFAULT_ATTRIBUTES = {
      wait_condition: -> {},
      base_message: "",
      interval: 0.4,
      message_continuations: ["", ".", "..", "..."]
    }

    def initialize(attributes = {})
      DEFAULT_ATTRIBUTES.merge(attributes).each do |key, value|
        public_send("#{key}=", value)
      end
      self.started = false
      self.counter = 0
    end

    def start
      fail already_started_message if started
      self.started = true

      Thread.new do
        loop do
          break if wait_condition.call(counter)
          print_message
          sleep interval
          self.counter += 1
        end
        self.started = false
      end
    end

    private

    def print_message
      message_continuation = message_continuations[counter] || begin
        message_continuations[counter % message_continuations.size]
      end
      print "\r#{base_message}#{message_continuation}"
    end

    def already_started_message
      "Please don't start this text spinner while is running. It can cause race conditions."
    end
  end
end

Version data entries

24 entries across 24 versions & 1 rubygems

Version Path
potassium-7.2.0 lib/potassium/text_spinner.rb
potassium-7.1.0 lib/potassium/text_spinner.rb
potassium-7.0.0 lib/potassium/text_spinner.rb
potassium-6.7.0 lib/potassium/text_spinner.rb
potassium-6.6.0 lib/potassium/text_spinner.rb
potassium-6.5.0 lib/potassium/text_spinner.rb
potassium-6.4.0 lib/potassium/text_spinner.rb
potassium-6.3.0 lib/potassium/text_spinner.rb
potassium-6.2.0 lib/potassium/text_spinner.rb
potassium-6.1.0 lib/potassium/text_spinner.rb
potassium-6.0.0 lib/potassium/text_spinner.rb
potassium-5.2.3 lib/potassium/text_spinner.rb
potassium-5.2.2 lib/potassium/text_spinner.rb
potassium-5.2.1 lib/potassium/text_spinner.rb
potassium-5.2.0 lib/potassium/text_spinner.rb
potassium-5.1.4 lib/potassium/text_spinner.rb
potassium-5.1.3 lib/potassium/text_spinner.rb
potassium-5.1.2 lib/potassium/text_spinner.rb
potassium-5.1.1 lib/potassium/text_spinner.rb
potassium-3.0.0 lib/potassium/text_spinner.rb