Created
December 18, 2013 18:14
-
-
Save meagar/8027073 to your computer and use it in GitHub Desktop.
Simple rake progress bar
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
# Use: | |
# | |
# # Pass an emuerable to #new | |
# | |
# users = User.active | |
# RakeProgrssBar.new(users) do |user| | |
# user.do_something_amazing | |
# end | |
# | |
# | |
# # Or, pass any iterator to #new; ie, each_with_index | |
# | |
# users = User.active | |
# RakeProgressBar.new(users.each_with_index) do |user,index| | |
# user.something_else_awesome | |
# end | |
# | |
# | |
# # Or, store progress_bar and iterate with #each later | |
# | |
# progress_bar = RakeProgressBar.new(users.active) | |
# | |
# progress_bar.each do |user| | |
# user.something_else_again | |
# end | |
# | |
# | |
# As always, use CTRL-C to abort | |
# | |
class RakeProgressBar | |
attr_reader :iterator, :count, :width | |
def initialize(iterator, options = {}, &block) | |
@iterator = iterator | |
@count = options[:count] || iterator.count | |
@width = options[:width] || 70 # TODO figure out console width | |
each(&block) if block_given? | |
end | |
def each | |
print "\n" | |
time_start = Time.now | |
index = 0 | |
iterator.each do |*args| | |
index += 1 | |
progress = ((index.to_f / count) * width).to_i | |
elapsed = Time.now - time_start | |
remaining = (elapsed.to_f / index) * count - index | |
print "Elapsed: #{format_time elapsed} | Remaining: #{format_time remaining}\n" | |
print "[#{'#' * progress}#{'-' * (width - progress)}]" | |
print "(#{index} / #{count})" | |
yield *args | |
cursor_up | |
end | |
print "\n" | |
end | |
def cursor_up | |
print "\r" # move to beginning of current line | |
print "\e[0k" # clear line | |
print "\e[0A" # move up to previous line | |
print "\e[0k" # clear line | |
end | |
def format_time(time) | |
# TODO Fails if `time` is more than 24 hours... | |
Time.at(time).gmtime.strftime('%H:%M:%S') | |
end | |
end | |
=begin | |
require './lib/rake_progress_bar' | |
desc "Test the RakeProgressBar thingy" | |
task :test_progress_bar do | |
puts "Looping 1000 times with a .1 second delay" | |
RakeProgressBar.new((1..1000).each_with_index).each do |i| | |
sleep 0.1 | |
# nothing | |
end | |
puts "Done!" | |
end | |
=end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment