Created
December 14, 2009 19:35
-
-
Save kdwinter/256346 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Ruby/ProgressBar - a text progress bar library | |
# | |
# Copyright (C) 2001 Satoru Takabayashi <satoru@namazu.org> | |
# All rights reserved. | |
# This is free software with ABSOLUTELY NO WARRANTY. | |
# | |
# You can redistribute it and/or modify it under the terms | |
# of Ruby's licence. | |
# | |
class ProgressBar | |
VERSION = "0.3" | |
def initialize title, total, out = STDERR | |
@title = title | |
@total = total | |
@out = out | |
@current = 0 | |
@previous = 0 | |
@is_finished = false | |
@start_time = Time.now | |
@bar = '###########################' | |
show_progress | |
end | |
def format_time t | |
t = t.to_i | |
sec = t % 60 | |
min = (t / 60) % 60 | |
hour = t / 3600 | |
sprintf('%02d:%02d:%02d', hour, min, sec); | |
end | |
# ETA stands for Estimated Time of Arrival. | |
def eta | |
if @current == 0 | |
'ETA: --:--:--' | |
else | |
elapsed = Time.now - @start_time | |
eta = elapsed * @total / @current - elapsed; | |
sprintf("ETA: %s", format_time(eta)) | |
end | |
end | |
def elapsed | |
elapsed = Time.now - @start_time | |
sprintf("Time: %s", format_time(elapsed)) | |
end | |
def time | |
@is_finished ? elapsed : eta | |
end | |
def eol | |
@is_finished ? "\n" : "\r" | |
end | |
def bar percentage | |
len = percentage * @bar.length / 100 | |
sprintf('[%.*s%*s]', len, @bar, @bar.length - len, '') | |
end | |
def show percentage | |
@out.printf('%-14s %3d%% %s %s%s', | |
@title[0,13] + ':', | |
percentage, | |
bar(percentage), | |
time, | |
eol) | |
end | |
def show_progress | |
if @total.zero? | |
cur_percentage = 100 | |
prev_percentage = 0 | |
else | |
cur_percentage = (@current * 100 / @total).to_i | |
prev_percentage = (@previous * 100 / @total).to_i | |
end | |
if cur_percentage > prev_percentage || @is_finished | |
show(cur_percentage) | |
end | |
end | |
public | |
def finish | |
@current = @total | |
@is_finished = true | |
show_progress | |
end | |
def set count | |
if count < 0 || count > @total | |
raise "invalid count: #{count} (total: #{total})" | |
end | |
@current = count | |
show_progress | |
@previous = @current | |
end | |
def inc step = 1 | |
@current += step | |
@current = @total if @current > @total | |
show_progress | |
@previous = @current | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment