Skip to content

Instantly share code, notes, and snippets.

@aqab
Forked from avdi/countdown_prompt.rb
Created July 17, 2009 19:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aqab/149231 to your computer and use it in GitHub Desktop.
Save aqab/149231 to your computer and use it in GitHub Desktop.
command-line animation
# Forked from gist: 148765
#
# Removed question and default value
# Renamed main method
# Put the 'ensure' clause within its own begin/end block
# Added a constant
#
# TO DO: increase animation speed
require 'rubygems'
require 'termios'
ANIMATION = %W{- / | \\}
def animate_with_timeout(seconds)
print 'Press any key to exit: '
begin
with_unbuffered_input($stdin) do
countdown_from(seconds) do |seconds_left|
write_then_erase_prompt(seconds_left) do
wait_for_input($stdin, seconds_left % 1) do
return 'bye...'
end
end
end
end
ensure
$stdout.puts
end
end # ask_with_countdown_to_default
def with_unbuffered_input(input = $stdin)
begin
old_attributes = Termios.tcgetattr(input)
new_attributes = old_attributes.dup
new_attributes.lflag &= ~Termios::ECHO
new_attributes.lflag &= ~Termios::ICANON
Termios::tcsetattr(input, Termios::TCSANOW, new_attributes)
yield
ensure
Termios::tcsetattr(input, Termios::TCSANOW, old_attributes)
end
end # with_unbuffered_input
def countdown_from(seconds_left)
start_time = Time.now
end_time = start_time + seconds_left
begin
yield(seconds_left)
seconds_left = end_time - Time.now
end while seconds_left > 0.0
end # countdown_from
def write_then_erase_prompt(seconds_left)
prompt = ANIMATION[ seconds_left.to_i % 4 ]
prompt_length = prompt.length
$stdout.write(prompt)
$stdout.flush
yield
$stdout.write("\b" * prompt_length)
$stdout.flush
end # write_then_erase_prompt
def wait_for_input(input, timeout)
# Wait until input is available
if select([input], [], [], timeout)
yield
end
end # wait_for_input
# :SAMPLE: usage
puts animate_with_timeout(60.0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment