Last active
June 6, 2016 15:43
-
-
Save emad-elsaid/f866c89d8ca4d7983e8b403099ac3d20 to your computer and use it in GitHub Desktop.
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
# manages your string in terminal, each call to rendr will clear the old string | |
# and print the new one | |
# Extracted from | |
# https://github.com/arlimus/inquirer.rb/blob/master/lib/inquirer/utils/iohelper.rb | |
module Buffer | |
extend self | |
CARRIAGE_RETURN = "\r".freeze | |
LINE_UP = "\e[A".freeze | |
CLEAR_LINE = "\e[0K".freeze | |
CHAR_LEFT = "\e[D".freeze | |
CHAR_RIGHT = "\e[C".freeze | |
def render(string) | |
clear | |
@rendered = string.to_s | |
print @rendered | |
end | |
def clear | |
n = @rendered.to_s.scan(/\n/).length | |
print CARRIAGE_RETURN + (LINE_UP + CLEAR_LINE) * n + CLEAR_LINE | |
end | |
module_function :render | |
module_function :clear | |
end | |
class Row < Array | |
def to_s | |
map(&:to_s).join + "\n" | |
end | |
end | |
class ProgressBar | |
# https://en.wikipedia.org/wiki/Code_page_437 | |
BACKGROUND = "\u2591".freeze | |
FOREGROUND = "\u2593".freeze | |
attr_accessor :width, :value | |
def initialize(width, value = 0) | |
@width = width | |
@value = value | |
end | |
def background_width | |
width - value >= 0 ? width - value : 0 | |
end | |
def foreground_width | |
[width, value].min | |
end | |
def to_s | |
FOREGROUND * foreground_width + BACKGROUND * background_width | |
end | |
end | |
# ==================================== | |
bar = ProgressBar.new(20, 0) | |
output = Row.new(["Hello World...", bar]) | |
Buffer.render output | |
sleep 2 | |
output[0] = "This changed, and will change in 2 second" | |
sleep 2 | |
10.times do | |
bar.value += 2 | |
Buffer.render output | |
sleep(1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment