Skip to content

Instantly share code, notes, and snippets.

@elizabrock
Last active December 17, 2015 12:09
Show Gist options
  • Save elizabrock/5608192 to your computer and use it in GitHub Desktop.
Save elizabrock/5608192 to your computer and use it in GitHub Desktop.
Countdown (with output always shown at the top of the terminal)
class Countdown
BELL = "\a"
COLORS = {
'black' => 30,
'red' => 31,
'green' => 32,
'yellow' => 33,
'blue' => 34,
'magenta' => 35,
'cyan' => 36,
'white' => 37
}
def self.for total_time_in_minutes
total_time_in_seconds = total_time_in_minutes * 60
end_time = Time.now + total_time_in_seconds
print choose_color(total_time_in_seconds, total_time_in_seconds) + format_time(total_time_in_seconds)
print fill
while Time.now < end_time
time_remaining = end_time - Time.now
print backtrack
print choose_color(total_time_in_seconds, time_remaining) + format_time(time_remaining)
print fill
sleep 1
end
print backtrack
puts "\e[#{COLORS['blue']}mDone!" + BELL
end
private
def self.terminal_height
`tput lines`.to_i
end
def self.backtrack
"\e[#{terminal_height}A" + " " * 8 + "\e[#{8}D"
end
def self.fill
output = ""
(terminal_height - 1).times do
output << "\n"
end
output
end
def self.format_time time
seconds = time % 60
minutes = (time / 60) % 60
hours = time / 3600
formatted_string = sprintf("%02d:%02d:%02d", hours, minutes, seconds);
end
def self.choose_color total_time_in_seconds, seconds_remaining
percentage_remaining = 100 * seconds_remaining / total_time_in_seconds
if percentage_remaining < 5
color_code = COLORS['red']
elsif percentage_remaining < 10
color_code = COLORS['yellow']
else
color_code = COLORS['green']
end
"\e[#{color_code}m"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment