Class: GDKBox::ProgressBar
- Inherits:
-
Object
- Object
- GDKBox::ProgressBar
- Defined in:
- lib/gdkbox/progress_bar.rb
Overview
A single-line terminal progress bar.
Rendering is only enabled on a TTY so piped or JSON output stays clean; on a
non-TTY the bar is silent and the caller's regular say messages carry the
story instead. The bar redraws in place with a carriage return until
finish moves the cursor to the next line.
Instance Method Summary collapse
- #enabled? ⇒ Boolean
-
#finish(label = nil) ⇒ Object
Fill the bar and drop to a fresh line so later output is not overwritten.
-
#initialize(out: $stderr, width: 30, enabled: nil) ⇒ ProgressBar
constructor
A new instance of ProgressBar.
-
#update(fraction, label = nil) ⇒ Object
Redraw the bar at the given fraction (clamped to 0.0..1.0) with an optional trailing label (e.g. "12/40 layers").
Constructor Details
#initialize(out: $stderr, width: 30, enabled: nil) ⇒ ProgressBar
Returns a new instance of ProgressBar.
11 12 13 14 15 |
# File 'lib/gdkbox/progress_bar.rb', line 11 def initialize(out: $stderr, width: 30, enabled: nil) @out = out @width = width @enabled = enabled.nil? ? (out.respond_to?(:tty?) && out.tty?) : enabled end |
Instance Method Details
#enabled? ⇒ Boolean
17 18 19 |
# File 'lib/gdkbox/progress_bar.rb', line 17 def enabled? @enabled end |
#finish(label = nil) ⇒ Object
Fill the bar and drop to a fresh line so later output is not overwritten.
36 37 38 39 40 41 42 |
# File 'lib/gdkbox/progress_bar.rb', line 36 def finish(label = nil) return unless @enabled update(1.0, label) @out.print("\n") @out.flush end |
#update(fraction, label = nil) ⇒ Object
Redraw the bar at the given fraction (clamped to 0.0..1.0) with an optional trailing label (e.g. "12/40 layers").
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/gdkbox/progress_bar.rb', line 23 def update(fraction, label = nil) return unless @enabled fraction = [[fraction.to_f, 0.0].max, 1.0].min filled = (fraction * @width).round = ("█" * filled) + ("░" * (@width - filled)) text = format("\r[%s] %3d%%", , (fraction * 100).round) text += " #{label}" if label && !label.empty? @out.print(text) @out.flush end |