Skip to content
Projects

bodrovis/kawaii_progress

View on GitHub

About

A lightweight, thread-safe progress bar for Ruby

Developer Tools

How these counts are measured

What you can do

  • Zero third-party runtime dependencies and Ruby 3.4+ support.
  • Thread-safe updates to a single progress bar, even from multiple workers.
  • Configurable refresh intervals to avoid overwhelming the terminal.
  • Custom symbols and format templates with progress, speed, elapsed time, and ETA.

Measured star growth

in 24h
Collecting history
in 7 days
Collecting history
in 15 days
Collecting history
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.md

Original

KawaiiProgress (˶ᵔ ᵕ ᵔ˶)

Gem Version CI Code Coverage Maintainability

A little Ruby gem for making long-running tasks a little less boring.

KawaiiProgress gives you customizable terminal progress bars, estimated completion times, and thread-safe updates without pulling in a pile of dependencies. Feed some cats, process a million records, or watch your background workers do their thing. At least now you know how far they've got.

Processing   [████████████░░░░░░░░░░░░░░░░░░] 40/100 40% ETA 15s
Downloading  [========------------] 40% | 12.5 items/s
Feeding cats ♥♥♥♥♥♥♡♡♡♡ 6/10 | ETA 2s

Small gem. Big kawaii energy. ♡

Find a real usage example in the nya_pr gem.

Features

  • Zero third-party runtime dependencies and Ruby 3.4+ support.
  • Thread-safe updates to a single progress bar, even from multiple workers.
  • Configurable refresh intervals to avoid overwhelming the terminal.
  • Custom symbols and format templates with progress, speed, elapsed time, and ETA.
  • Automatic terminal width detection and resizing (optional).
  • Automatic TTY detection and final-only output when redirected to a file or CI log.
  • An enumerable helper that takes care of updating and finishing the bar for you.
  • Immutable progress snapshots, injectable monotonic clocks, and custom renderers.

Installation

Add the gem to your project:

bundle add kawaii_progress

Or install it directly:

gem install kawaii_progress

KawaiiProgress requires Ruby 3.4 or newer.

Quick start

The easiest way to track a collection is with KawaiiProgress.each:

require 'kawaii_progress'

KawaiiProgress.each(1..50, title: 'Feeding cats') do |_cat|
  sleep 0.05 # Pretend we're doing something useful.
end

That's it. KawaiiProgress determines the total, advances the bar after each completed iteration, and finishes it when the loop exits.

Manual progress updates

For more control, create a KawaiiProgress::Bar yourself:

require 'kawaii_progress'

bar = KawaiiProgress::Bar.new('Processing', total: 100)

begin
  100.times do
    sleep 0.03
    bar.advance
  end
ensure
  bar.finish
end

advance increments the counter by one by default. Pass a non-negative integer to advance by a different amount:

bar.advance(5)

The counter never exceeds the specified total. Reaching the total redraws the bar but does not automatically finish it. Call finish to finalize the output and freeze the elapsed time.

You can finish a bar early, too. If your task stops at 42%, the bar will still say 42%. No fake achievements here.

Calling finish more than once has no effect, and valid progress updates after finishing are ignored.

Make it kawaii

The default block characters are nice, but why stop there?

KawaiiProgress.each(
  1..50,
  title: 'Feeding cats',
  width: 10,
  filled: '♥',
  empty: '♡',
  format: '%{title} %{bar} %{percentage}%% | ETA %{eta}'
) do |_cat|
  sleep 0.05
end
Feeding cats ♥♥♥♥♥♥♡♡♡♡ 60% | ETA 1s

Prefer ASCII? We have you covered:

bar = KawaiiProgress::Bar.new(
  'Downloading',
  total: 100,
  width: 20,
  filled: '=',
  empty: '-',
  format: '%{title} [%{bar}] %{percentage}%% | %{rate} items/s'
)
Downloading [========------------] 40% | 12.5 items/s

You don't even have to include the graphical bar in your template. A plain counter, a timer, or a line full of hearts is perfectly fine.

Format placeholders

Templates use Ruby's named format tokens. The default template is:

'%{title} [%{bar}] %{current}/%{total} %{percentage}%% ETA %{eta}'
Placeholder Description Example
%{title} Task title Feeding cats
%{bar} Graphical progress bar ♥♥♥♡♡
%{current} Number of completed items 60
%{total} Total number of items 100
%{percentage} Rounded completion percentage 60
%{eta} Estimated remaining time 20s
%{elapsed} Elapsed time 30s
%{rate} Average items processed per second 2.0
%% Literal percent sign %

Remember to use %% if you want a literal percent sign in the output. Unknown named placeholders raise a KeyError when the template is rendered.

Configuration

Pass these options to Bar.new or, where applicable, to KawaiiProgress.each:

Option Default Description
total Required for Bar Non-negative integer representing the expected work. In .each, inferred from the collection when possible.
enabled true Enables rendering. When false, progress is still tracked.
width 30 Positive number of bar segments, or :auto.
filled '█' Non-empty string representing a completed segment.
empty '░' Non-empty string representing an incomplete segment.
format Default template above Template used to build the progress line.
output $stderr Output stream supporting print, puts, and flush.
interactive nil Automatically detects TTY when nil; override with true or false.
refresh_interval 0.1 Minimum time between regular redraws, in seconds. Use 0 to disable throttling.
clock KawaiiProgress::Clock Custom monotonic clock exposing a now method returning seconds.
renderer Default renderer Custom object implementing render(snapshot) and finish(snapshot).

Bar.new takes the title as its first positional argument. KawaiiProgress.each accepts title: as a keyword argument, defaulting to 'Processing'.

Automatic width

Use width: :auto to let the bar adapt to the terminal and the rest of your format template:

KawaiiProgress.each(1..100, width: :auto) do
  sleep 0.05
end

The width is recalculated when the bar is redrawn. If the terminal dimensions are unavailable or output is non-interactive, KawaiiProgress falls back to 30 segments.

Display width is estimated using Unicode grapheme clusters and ignores ANSI styling sequences. Wide characters and emoji may take up more than one terminal column, so automatic sizing is approximate. A very long title or template can still wrap even when the bar itself has no segments. ASCII symbols are the safest option when exact alignment matters.

Refresh intervals

Updating a counter is cheap. Redrawing a terminal thousands of times per second? Not so much.

KawaiiProgress updates the counter on every valid advance call while the task is running, but normally redraws the bar no more than once per refresh interval. The initial and final states, as well as the transition to the specified total, bypass throttling.

bar = KawaiiProgress::Bar.new(
  'Crunching numbers',
  total: 100_000,
  refresh_interval: 0.25
)

100_000.times { bar.advance }
bar.finish

There are no background refresh threads. Redraws happen in response to progress updates, so the display will not update itself while your task is idle.

Output and interactive mode

By default, progress is written to standard error ($stderr), leaving standard output available for your application's actual results.

interactive Behavior
nil Detect whether the output is a TTY.
true Redraw the current line using ANSI escape sequences.
false Suppress intermediate output and write a single final line.

For example, capture the final progress line in memory:

require 'stringio'
require 'kawaii_progress'

output = StringIO.new

KawaiiProgress.each(1..10, output: output) do
  sleep 0.01
end

puts output.string

Or set enabled: false to suppress rendering entirely without losing progress tracking. A task with total: 0 also produces no progress output.

Working with collections

KawaiiProgress.each works with arrays, hashes, ranges, and other objects that implement each.

If the collection exposes a non-negative integer size, KawaiiProgress uses it as the total. Otherwise, supply total: explicitly:

KawaiiProgress.each(
  File.foreach('records.txt'),
  title: 'Reading records',
  total: 1_000
) do |line|
  process(line) # Your own processing method.
end

KawaiiProgress does not traverse a collection in advance to count its items. Tasks with an unknown total require an explicit estimate; the total does not limit how many items are actually iterated over.

Without a block, .each returns an Enumerator, so you can chain standard Ruby enumerable methods:

squares = KawaiiProgress.each(1..10, title: 'Doing maths').map do |number|
  number**2
end

The progress bar is created when iteration begins. During block-based iteration, exceptions propagate normally and the bar is finalized when the loop exits, including on break. Only iterations that return normally are counted as completed.

Concurrent updates

Got a bunch of workers? Let them share one progress bar:

bar = KawaiiProgress::Bar.new('Parallel workers', total: 100)

begin
  threads = Array.new(4) do
    Thread.new do
      25.times do
        sleep 0.04
        bar.advance
      end
    end
  end

  threads.each(&:value)
ensure
  bar.finish
end

Updates and rendering are synchronized within each bar to prevent lost increments and interleaved redraws from its workers. Independent bars writing to the same stream are not coordinated; multi-line progress displays are not supported at present.

Inspecting progress

You can read the current state through the bar's public methods:

bar.current     # Completed items
bar.total       # Expected items
bar.progress    # Completion ratio, e.g. 0.4
bar.percentage  # Rounded percentage, e.g. 40
bar.elapsed     # Elapsed seconds
bar.rate        # Average items per second
bar.eta         # Estimated remaining seconds, or nil
bar.enabled?    # Whether rendering is enabled
bar.finished?   # Whether finish has been called

If you need several consistent metrics at once, capture an immutable snapshot:

state = bar.snapshot

puts "Processed #{state.current}/#{state.total}"
puts "Average speed: #{state.rate.round(2)} items/s"
puts "Elapsed: #{state.elapsed.round(2)}s"

All timing metrics in a snapshot are based on the same captured timestamp. Later updates do not change an existing snapshot. The default clock is monotonic, so system clock adjustments do not affect elapsed time calculations.

ETA is estimated using the average processing rate since the task began. It is unknown until a positive rate can be calculated. When a task is finished early, its actual progress and timing metrics are preserved.

Custom renderers

Want to send progress somewhere other than a terminal? Implement your own renderer:

class PlainRenderer
  def render(snapshot)
    puts "#{snapshot.title}: #{snapshot.percentage}%"
  end

  def finish(snapshot)
    render(snapshot)
  end
end

bar = KawaiiProgress::Bar.new(
  'Processing',
  total: 10,
  renderer: PlainRenderer.new
)

10.times { bar.advance }
bar.finish

A renderer receives a KawaiiProgress::Snapshot, not the mutable bar itself. Configure custom renderers directly rather than combining renderer: with built-in rendering options such as width: or format:.

Renderer callbacks run synchronously under the bar's lock during updates and finalization. Do not call synchronized methods on the same bar from inside a renderer callback.

Samples

Want to see the little thing in action before using it in your own project? Run any of the scripts in samples/ from the repository root:

ruby samples/basic.rb
ruby samples/custom_format.rb
ruby samples/auto_width.rb
ruby samples/threads.rb
Sample What it demonstrates
basic.rb Manual updates and finalization.
custom_format.rb ASCII bars, hearts, custom templates, and variable delays.
auto_width.rb Resize your terminal while the task runs.
enumerable.rb Enumerable integration, map, and explicitly sized sources.
threads.rb Multiple workers sharing a single bar.
throttling.rb 100,000 updates without 100,000 redraws.
early_finish.rb Exceptions and interrupted iteration.
non_interactive.rb Final-only output, captured output, and disabled rendering.

The samples load the local library directly. No gem installation, network requests, or actual cats are required. Sadly.

Development and contributing

Bug reports, ideas, and pull requests are welcome! To get started, clone the repository and install its development dependencies:

bundle install
bundle exec rspec
bundle exec rubocop
bundle exec reek

If you're reporting a terminal rendering issue, please include your Ruby version, operating system, terminal, and a small reproducible example. Terminal quirks can be surprisingly un-kawaii.

License

KawaiiProgress is available under the MIT License.

Made with Ruby, a little patience, and a whole lot of ♡.

Explore related projects

Loading…