Skip to content

Instantly share code, notes, and snippets.

@thechrisoshow
Last active March 19, 2018 18:11
Show Gist options
  • Save thechrisoshow/8da9c25c67f08896458e6bcc3e2ac8f4 to your computer and use it in GitHub Desktop.
Save thechrisoshow/8da9c25c67f08896458e6bcc3e2ac8f4 to your computer and use it in GitHub Desktop.
Heroku style spinner
# Shamelessly stolen from https://gist.github.com/ileitch/1459987
module InterruptibleSleep
def interruptible_sleep(seconds)
@sleep_check, @sleep_interrupt = IO.pipe
IO.select([@sleep_check], nil, nil, seconds)
end
def interrupt_sleep
@sleep_interrupt.close if @sleep_interrupt
end
end
require 'interruptible_sleep'
class Spinner
include InterruptibleSleep
GLYPHS = %w(⣾ ⣷ ⣯ ⣟ ⡿ ⢿ ⣻ ⣽).reverse
INTERVAL_DURATION = 0.07
def initialize
@current_glyph = 0
end
def progress
loop do
increment
print "\r#{glyph} "
interruptible_sleep(INTERVAL_DURATION)
end
end
def stop
print "\r"
interrupt_sleep
end
def self.show_progress(&block)
process = fork(&block)
progress = fork do
progress_indicator = Spinner.new
progress_indicator.progress
end
Process.wait(process)
Process.kill("HUP", progress)
print "\r"
end
private
def increment
@current_glyph = @current_glyph + 1
@current_glyph = 0 if @current_glyph >= GLYPHS.length
end
def glyph
GLYPHS[@current_glyph]
end
end
@thechrisoshow
Copy link
Author

Use it with:

Spinner.show_progress do
  sleep 1
end
puts "Finished!"

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