Class: ProgressBar

Inherits:
Object
  • Object
show all
Defined in:
lib/progress_bar.rb,
lib/progress_bar/version.rb,
lib/progress_bar/with_progress.rb

Defined Under Namespace

Modules: WithProgress

Constant Summary collapse

Error =
Class.new(StandardError)
ArgumentError =
Class.new(Error)
VERSION =
"1.3.3"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ ProgressBar

Returns a new instance of ProgressBar.

Raises:


12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/progress_bar.rb', line 12

def initialize(*args)
  @count      = 0
  @max        = 100
  @meters     = [:bar, :counter, :percentage, :elapsed, :eta, :rate]

  @max = args.shift if args.first.is_a? Numeric
  raise ArgumentError, "Max must be a positive integer" unless @max >= 0

  @meters = args unless args.empty?

  @last_write = ::Time.at(0)
  @start      = ::Time.now

  @hl = HighLine.new
  @terminal_width = 80
  @last_width_adjustment = ::Time.at(0)
end

Instance Attribute Details

#countObject

Returns the value of attribute count


10
11
12
# File 'lib/progress_bar.rb', line 10

def count
  @count
end

#maxObject

Returns the value of attribute max


10
11
12
# File 'lib/progress_bar.rb', line 10

def max
  @max
end

#metersObject

Returns the value of attribute meters


10
11
12
# File 'lib/progress_bar.rb', line 10

def meters
  @meters
end

Instance Method Details

#elapsedObject


62
63
64
# File 'lib/progress_bar.rb', line 62

def elapsed
  ::Time.now - @start
end

#etaObject


74
75
76
77
78
79
80
# File 'lib/progress_bar.rb', line 74

def eta
  if count > 0
    remaining / rate
  else
    0
  end
end

#increment!(count = 1) ⇒ Object


30
31
32
33
34
35
36
37
# File 'lib/progress_bar.rb', line 30

def increment!(count = 1)
  @count += count
  now = ::Time.now
  if (now - @last_write) > 0.2 || @count >= max
    write
    @last_write = now
  end
end

#percentageObject


58
59
60
# File 'lib/progress_bar.rb', line 58

def percentage
  ratio * 100
end

#puts(text) ⇒ Object


39
40
41
42
43
44
# File 'lib/progress_bar.rb', line 39

def puts(text)
  clear!
  $stderr.write(text)
  $stderr.puts
  write
end

#rateObject


66
67
68
69
70
71
72
# File 'lib/progress_bar.rb', line 66

def rate
  if count > 0
    count / elapsed
  else
    0
  end
end

#ratioObject


54
55
56
# File 'lib/progress_bar.rb', line 54

def ratio
  [count.to_f / max, 1.0].min # never go above 1, even if count > max
end

#remainingObject


50
51
52
# File 'lib/progress_bar.rb', line 50

def remaining
  max - count
end

#to_sObject


82
83
84
85
86
87
# File 'lib/progress_bar.rb', line 82

def to_s
  self.count = max if count > max
  meters.inject(String.new) do |text, meter|
    text << "#{render(meter)} "
  end.strip
end

#writeObject


46
47
48
# File 'lib/progress_bar.rb', line 46

def write
  print "\r" + to_s
end