lib/rmega/progress.rb in rmega-0.1.0 vs lib/rmega/progress.rb in rmega-0.1.1
- old
+ new
@@ -1,34 +1,49 @@
module Rmega
class Progress
def initialize(params)
- @filesize = params[:filesize]
- @verb = params[:verb].capitalize
- @progress = 0
+ @total = params[:total]
+ @caption = params[:caption]
+ @bytes = 0
+ @start_time = Time.now
- render
+ show
end
- def render
- percentage = (100.0 * @progress / @filesize).round(2)
- message = "#{@verb} in progress #{format_bytes(@progress)} of #{format_bytes(@filesize)} (#{percentage}%)"
- rtrn = "\n" if @filesize == @progress
+ def show
+ percentage = (100.0 * @bytes / @total).round(2)
- print "\r#{' '*(message.size + 15)}\r#{message}#{rtrn}"
+ 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
- def increment(bytes)
- @progress += bytes
+ def elapsed_time
+ (Time.now - @start_time).round(2)
+ end
- render
+ def ended?
+ @total == @bytes
end
- def format_bytes(bytes, round = 2)
+ def increment(bytes)
+ @bytes += bytes
+ show
+ end
+
+ 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]}"
+ "#{value.round(round)} #{units[e]}"
end
end
end