Created
October 20, 2015 12:56
-
-
Save Kosmas/03ea8adbc813b1b072dc to your computer and use it in GitHub Desktop.
display percentages in a rake task
This file contains hidden or 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
def calculate_perc(i, total) | |
(i * 100 / total).to_i | |
end | |
def rate_limit_1_perc?(perc, last_perc, last_updated) | |
# Changes of at least 1% | |
# once every 20 seconds | |
perc > last_perc && last_updated < Time.now.ago(20.seconds) | |
end | |
def rate_limit_5_perc?(perc, last_perc, last_updated) | |
# Changes >5% | |
# once every 10 seconds | |
perc.divmod(5).first > last_perc.divmod(5).first && | |
last_updated < Time.now.ago(10.seconds) | |
end | |
def show_start_end_perc?(i, total) | |
# Show 0% and 100% | |
i == 1 || i == total | |
end | |
def main_loop | |
i = 1 | |
last_perc ||= 0 | |
last_updated ||= Time.now | |
total = e_batch.e_base_records.size | |
array_of_records.each do |rec| | |
if show_progress | |
perc = calculate_perc(i, total) | |
if rate_limit_1_perc?(perc, last_perc, last_updated) || | |
rate_limit_5_perc?(perc, last_perc, last_updated) || | |
show_start_end_perc?(i, total) | |
print "#{perc}% " | |
$stdout.flush | |
last_updated = Time.now | |
end | |
i += 1 | |
last_perc = perc | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment