From d02410fae49ced0e9b5ecc0b4a4f82fe5c78b8af Mon Sep 17 00:00:00 2001 From: Alex Watt Date: Wed, 23 Aug 2023 05:58:19 -0400 Subject: [PATCH] ProgressBar#current= supports indeterminate progress bars too --- CHANGELOG.md | 5 +++++ lib/tty/progressbar.rb | 6 +++++- spec/unit/set_current_spec.rb | 15 +++++++++++++++ 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 6324ea6..817d898 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Change log +## Unreleased + +### Fixed +* Fix ProgressBar#current= for indeterminate progress bar by Alex Watt (@alexcwatt) + ## [v0.18.2] - 2021-03-08 ### Fixed diff --git a/lib/tty/progressbar.rb b/lib/tty/progressbar.rb index f176ffc..db41704 100644 --- a/lib/tty/progressbar.rb +++ b/lib/tty/progressbar.rb @@ -290,7 +290,11 @@ def update(options = {}) # # @api public def current=(value) - value = [0, [value, total].min].max + unless value.is_a?(Numeric) + raise ArgumentError, "Expected a numeric value, got #{value.inspect} instead." + end + + value = [0, [value, total].compact.min].max advance(value - @current) end diff --git a/spec/unit/set_current_spec.rb b/spec/unit/set_current_spec.rb index fd7e5ef..77520c9 100644 --- a/spec/unit/set_current_spec.rb +++ b/spec/unit/set_current_spec.rb @@ -33,6 +33,15 @@ expect(progress.current).to eq(0) end + it "doesn't allow nil" do + progress = TTY::ProgressBar.new("[:bar]", output: output, total: 10) + expect { progress.current = nil }.to raise_error( + ArgumentError, + "Expected a numeric value, got nil instead." + ) + expect(progress.current).to eq(0) + end + it "cannot backtrack on finished" do progress = TTY::ProgressBar.new("[:bar]", output: output, total: 10) progress.current = 10 @@ -42,4 +51,10 @@ output.rewind expect(output.read).to eq("\e[1G[==========]\n") end + + it "allows setting progress when total is unknown" do + progress = TTY::ProgressBar.new("[:bar]", output: output, total: nil) + progress.current = 5 + expect(progress.current).to eq(5) + end end