Last active
November 24, 2016 09:45
-
-
Save am-kantox/8f0e1da833a893ac6df3c3589db7c1d4 to your computer and use it in GitHub Desktop.
ProgressBar in ruby (e. g. for console rakes.)
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
class ProgressBar | |
RUNNING = %W{๐ ๐ ๐ ๐ ๐}.freeze | |
attr_reader :count, :position | |
def initialize caption, count, running = RUNNING | |
@count = count | |
@caption = " #{caption} " | |
@running = running.cycle | |
@position = 0 | |
end | |
def tick | |
@now = Time.now if @position.zero? | |
@position += 1 | |
closing | |
opening | |
meter | |
end | |
############################################################################ | |
def self.test caption = 'Hello', count = 1024 | |
ProgressBar.new(caption, count).tap do |pb| | |
pb.count.times do | |
sleep 0.01 | |
pb.tick | |
end | |
end | |
end | |
############################################################################ | |
private | |
def opening(sym = '|') | |
print "\e[1G#{@caption}#{sym}" | |
end | |
def closing(sym = '|') | |
print "\e[#{$stdin.winsize.first}G#{sym}" | |
end | |
def meter(sym = '=') | |
print sym * (@position.to_f * ($stdin.winsize.first - @caption.length - 2) / @count) | |
if @position == @count | |
puts | |
# rubocop:disable Style/FormatString | |
puts "It took %s min %s sec" % (Time.now - @now).ceil.divmod(60) | |
# rubocop:enable Style/FormatString | |
else | |
print @running.next | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment