Skip to content

Instantly share code, notes, and snippets.

@kotay
Last active August 29, 2015 13:56
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 kotay/9001133 to your computer and use it in GitHub Desktop.
Save kotay/9001133 to your computer and use it in GitHub Desktop.
ruby console spinner
def with_spinner
finished = false
working = Mutex.new
spinner = Thread.new do
loop do
break if working.synchronize {finished}
["|","/","-","\\"].each do |glyph|
print "\r#{glyph}"
sleep 0.07
print "\b"
end
end
end
define_singleton_method(:puts) { |s| super("\b#{s}") }
yield
working.synchronize{ finished = true }
spinner.join
STDOUT.flush
end
puts "A"
with_spinner{ sleep 2; puts "starting..."; sleep 2 ; puts "stopped"; }
puts "B"
# wanted output while spinning:
# A
# /
# B
# wanted output after:
# A
# started...
# stopped
# B
# output without overriding puts method (line#14)
# A
# |starting...
# |stopped
# B
@kotay
Copy link
Author

kotay commented Feb 14, 2014

This little helper method works nicely for displaying a spinner until the block is finished. The only way I could get the block to print was to override the puts method in the block (line 14) to move the cursor back before printing. Is there a nice way to achieve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment