Last active
August 29, 2015 13:56
-
-
Save kotay/9001133 to your computer and use it in GitHub Desktop.
ruby console spinner
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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?