Sha256: 83cef7f02ba566cc4e26034d7238a01a05156f5134438b7db6c3ba3754c1a598

Contents?: true

Size: 973 Bytes

Versions: 25

Compression:

Stored size: 973 Bytes

Contents

# frozen_string_literal: true

#
# Copyright 2013 whiteleaf. All rights reserved.
#

class ProgressBar
  class OverRangeError < StandardError; end

  attr_reader :io

  def initialize(max, interval = 1, width = 50, char = "*", io: $stdout)
    @max = max == 0 ? 1.0 : max.to_f
    @interval = interval
    @width = width
    @char = char
    @counter = 0
    @io = io
  end

  def output(num)
    return if silent?
    if num > @max
      raise OverRangeError, "`#{num}` over `#{@max}(max)`"
    end
    @counter += 1
    return unless @counter % @interval == 0
    ratio = calc_ratio(num)
    now = (@width * ratio).round
    rest = @width - now
    io.stream.print format("[%s%s] %d%%\r", @char * now, " " * rest, (ratio * 100).round)
  end

  def clear
    return if silent?
    io.stream.print "\e[2K\r" # 行削除して行頭へ移動
  end

  def calc_ratio(num)
    num / @max
  end

  def silent?
    ENV["NAROU_ENV"] == "test" || !io.tty? || io.silent?
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
narou-3.9.1 lib/progressbar.rb
narou-3.9.0 lib/progressbar.rb
narou-3.8.2 lib/progressbar.rb
narou-3.8.1 lib/progressbar.rb
narou-3.8.0 lib/progressbar.rb
narou-3.7.2 lib/progressbar.rb
narou-3.7.1 lib/progressbar.rb
narou-3.7.0 lib/progressbar.rb
narou-3.6.0 lib/progressbar.rb
narou-3.5.1 lib/progressbar.rb
narou-3.5.0.1 lib/progressbar.rb
narou-3.5.0 lib/progressbar.rb
narou-3.4.8 lib/progressbar.rb
narou-3.4.7.1 lib/progressbar.rb
narou-3.4.7 lib/progressbar.rb
narou-3.4.6.1 lib/progressbar.rb
narou-3.4.6 lib/progressbar.rb
narou-3.4.5 lib/progressbar.rb
narou-3.4.3 lib/progressbar.rb
narou-3.4.2 lib/progressbar.rb