Class: ProgressBar

Inherits:
Object
  • Object
show all
Defined in:
lib/progressbar.rb

Overview

Copyright 2013 whiteleaf. All rights reserved.

Defined Under Namespace

Classes: OverRangeError

Instance Method Summary collapse

Constructor Details

#initialize(max, interval = 1, width = 50, char = "*") ⇒ ProgressBar

Returns a new instance of ProgressBar.



9
10
11
12
13
14
15
# File 'lib/progressbar.rb', line 9

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

Instance Method Details

#calc_ratio(num) ⇒ Object



35
36
37
# File 'lib/progressbar.rb', line 35

def calc_ratio(num)
  num / @max
end

#clearObject



30
31
32
33
# File 'lib/progressbar.rb', line 30

def clear
  return if $debug
  STDOUT.print " " * 79 + "\r"
end

#output(num) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/progressbar.rb', line 17

def output(num)
  return if $debug
  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
  STDOUT.print "[" + @char * now + ' ' * rest + "] #{(ratio * 100).round}%\r"
end