From c6f61b2f702b7b9680ed850f4e79bf30f31385fd 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 | 7 ++++++- spec/unit/set_current_spec.rb | 15 +++++++++++++++ 3 files changed, 26 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..7cc88c4 100644 --- a/lib/tty/progressbar.rb +++ b/lib/tty/progressbar.rb @@ -290,7 +290,12 @@ 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