Display a single or multiple progress bars in the terminal.
Display a single or multiple progress bars in the terminal.
A flexible and extensible progress bar for terminal applications.
TTY::ProgressBar provides independent progress bar component for TTY toolkit.
Add this line to your application's Gemfile:
gem "tty-progressbar"And then execute:
$ bundleOr install it yourself as:
$ gem install tty-progressbarTTY::ProgressBar requires only a format string with :bar token and total number of steps to completion:
bar = TTY::ProgressBar.new("downloading [:bar]", total: 30)Once initialized, use advance method to indicated progress:
30.times do
sleep(0.1)
bar.advance # by default increases by 1
endThis would produce the following animation in your terminal:
# downloading [======================= ]You can further change a progress bar behaviour and display by changing configuration options and using many predefined tokens and bar formats.
When you don't know the total yet, you can set it to nil to switch to indeterminate progress:
# downloading [ ]Use TTY::ProgressBar::Multi to display multiple parallel progress bars.
Declare a top level bar and then register child bars:
bars = TTY::ProgressBar::Multi.new("main [:bar] :percent")
bar1 = bars.register("one [:bar] :percent", total: 15)
bar2 = bars.register("two [:bar] :percent", total: 15)Then progress the child bars in parallel:
bars.start # starts all registered bars timers
th1 = Thread.new { 15.times { sleep(0.1); bar1.advance } }
th2 = Thread.new { 15.times { sleep(0.1); bar2.advance } }
[th1, th2].each { |t| t.join }A possible terminal output may look like this:
# ┌ main [=============== ] 50%
# ├── one [===== ] 34%
# └── two [========== ] 67%Once you have TTY::ProgressBar instance, you can progress the display by calling advance method. By default, it will increase by 1 but you can pass any number of steps, for instance, a number of bytes for a downloaded file:
bar.advance(1024)You can also pass negative steps if you wish to backtrack the progress:
bar.advance(-1)Note: If a progress bar has already finished then any negative steps will not set it back to desired value.
To simplify progressing over an enumerable you can use iterate which as a first argument accepts an Enumerable and as a second the amount to progress the bar with.
First, create a progress bar without a total which will be automatically updated for you once iteration starts:
bar = TTY::ProgressBar.new("[:bar]")Then, either directly iterate over a collection by yielding values to a block:
bar.iterate(30.times) { |v| ... }Or return an Enumerator:
progress = bar.iterate(30.times)
# => #By default, progress bar is advanced by 1 but you can change it by passing second argument:
bar.iterate(30.times, 5)One particularly useful application of iterate are Ruby infamous lazy enumerators, or slowly advancing enumerations, representing complex processes.
For example, an Enumerator that downloads content from a remote server chunk at a time:
downloader = Enumerator.new do |y|
start = 0
loop do
yield(download_from_server(start, CHUNK_SIZE))
raise StopIteration if download_finished?
start += CHUNK_SIZE
end
endWould be used with progress bar with the total size matching the content size like so:
bar = TTY::ProgressBar.new("[:bar]", total: content_size)
# you need to provide the total for the iterate to avoid calling enumerator.count
response = bar.iterate(downloader, CHUNK_SIZE).to_a.joinThis would result in progress bar advancing after each chunk up until all content has been downloaded, returning the result of the download in response variable.
Please run slow_process example to see this in action.
A progress doesn't have to start from zero. You can set it to a given value using current= method:
bar.current = 50Note: If a progress bar has already finished then setting current value will not have any effect.
In order to update overall completion of a progress bar as an exact percentage use the ratio= method. The method accepts values between 0 and 1 inclusive. For example, a ratio of 0.5 will attempt to set the progress bar halfway:
bar.ratio = 0.5You can set how many terminal columns will the :bar actually span excluding any other tokens and/or text.
For example, if you need the bar to be always 20 columns wide do:
bar.width = 20Or with configuration options:
bar = TTY::ProgressBar.new("[:bar]", width: 20)By default the timer for internal time estimation is started automatically when the advance method is called. However, if you require control on when the progression timer is started use start call:
bar.start # => sets timer and draws initial progress barOnce a progress bar has been started, you can change its configuration option(s) by calling update:
bar.update(complete: "+", frequency: 10)In order to immediately stop and finish progress of a bar call finish. This will finish drawing the progress by advancing it to 100% and returning to a new line.
bar.finishIn order to immediately stop a bar in the current position and thus prevent any further progress use stop:
bar.stopA running progress bar can be paused at the current position using pause method:
bar.pauseA paused progress bar will stop accumulating any time measurements like elapsed time. It also won't return to a new line, so a progress animation can be smoothly resumed.
In order to reset currently running or finished progress bar to its original configuration and initial position use reset like so:
bar.resetAfter resetting a progress bar, if you wish to draw and start a bar and its timers use start call.
When a bar is stopped or paused, you can continue its progression using the resume method.
bar.resumeA resumed progression will continue accumulating the total elapsed time without including time intervals for pausing or stopping.
During progression you can check whether a bar is finished or not by calling complete?. The bar will only return true if the progression finished successfully, otherwise false will be returned.
bar.complete? # => falseTo check whether a progress bar is paused or not use paused?:
bar.paused? # => trueTo check whether a progress bar is stopped or not use stopped?:
bar.stopped? # => trueYou can make a progress bar indeterminate by setting :total to nil. In this state, a progress bar animation is displayed to show unbounded task. You can check whether the progress bar is indeterminate with the indeterminate? method:
bar.indeterminate? # => falseIf you want to change a progress bar's current width, use resize and pass in a new desired length. However, if you don't provide any width the resize will use terminal current width as its base for scaling.
bar.resize # determine terminal width and scale accordingly
bar.resize(50) # will resize bar proportionately from this point onwardsTo handle automatic resizing you can trap :WINCH signal:
trap(:WINCH) { bar.resize }A progress bar fires events when it is progressing, paused, stopped or finished. You can register to listen for these events using the on message.
Every time an advance is called the :progress event gets fired which you can listen for inside a block. A first yielded argument is the actual amount of progress:
bar.on(:progress) { |amount| ... }When a progress bar finishes and completes then the :done event is fired. You can listen for this event:
bar.on(:done) { ... }Alternatively, when a progress bar gets stopped the :stopped event is fired. You can listen for this event:
bar.on(:stopped) { ... }Anytime a progress bar is paused the :paused event will be fired. To listen for this event do:
bar.on(:paused) { ... }There are number of configuration options that can be provided:
No open issues yet, or sync has not completed.