Class: ProgressBar

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

Constant Summary collapse

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ ProgressBar

Returns a new instance of ProgressBar

Raises:


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

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
end

Instance Attribute Details

#countObject

Returns the value of attribute count


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

def count
  @count
end

#maxObject

Returns the value of attribute max


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

def max
  @max
end

#metersObject

Returns the value of attribute meters


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

def meters
  @meters
end

Instance Method Details

#elapsedObject


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

def elapsed
  ::Time.now - @start
end

#etaObject


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

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

#increment!(count = 1) ⇒ Object


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

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

#percentageObject


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

def percentage
  ratio * 100
end

#rateObject


58
59
60
61
62
63
64
# File 'lib/progress_bar.rb', line 58

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

#ratioObject


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

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

#remainingObject


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

def remaining
  max - count
end

#to_sObject


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

def to_s
  self.count = max if count > max
  meters.inject("") do |text, meter|
    text << render(meter) + " "
  end.strip
end

#writeObject


37
38
39
40
# File 'lib/progress_bar.rb', line 37

def write
  clear!
  print to_s
end