Class: Rmega::Progress

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

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ Progress

Returns a new instance of Progress.


4
5
6
7
8
9
10
11
# File 'lib/rmega/progress.rb', line 4

def initialize(params)
  @total = params[:total]
  @caption = params[:caption]
  @bytes = 0
  @start_time = Time.now

  show
end

Instance Method Details

#elapsed_timeObject


28
29
30
# File 'lib/rmega/progress.rb', line 28

def elapsed_time
  (Time.now - @start_time).round(2)
end

#ended?Boolean

Returns:

  • (Boolean)

32
33
34
# File 'lib/rmega/progress.rb', line 32

def ended?
  @total == @bytes
end

#humanize(bytes, round = 2) ⇒ Object


41
42
43
44
45
46
47
# File 'lib/rmega/progress.rb', line 41

def humanize(bytes, round = 2)
  units = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']
  e = (bytes == 0 ? 0 : Math.log(bytes)) / Math.log(1024)
  value = bytes.to_f / (1024 ** e.floor)

  "#{value.round(round)} #{units[e]}"
end

#increment(bytes) ⇒ Object


36
37
38
39
# File 'lib/rmega/progress.rb', line 36

def increment(bytes)
  @bytes += bytes
  show
end

#showObject


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

def show
  percentage = (100.0 * @bytes / @total).round(2)

  message = "[#{@caption}] #{humanize(@bytes)} of #{humanize(@total)}"

  if ended?
    message << ". Completed in #{elapsed_time} sec.\n"
  else
    message << " (#{percentage}%)"
  end

  blank_line = ' ' * (message.size + 15)
  print "\r#{blank_line}\r#{message}"
end