diff --git a/lib/ruby-progressbar/calculators/smoothed_average.rb b/lib/ruby-progressbar/calculators/smoothed_average.rb index d6357f2..fbe365d 100644 --- a/lib/ruby-progressbar/calculators/smoothed_average.rb +++ b/lib/ruby-progressbar/calculators/smoothed_average.rb @@ -1,27 +1,47 @@ class ProgressBar module Calculators class SmoothedAverage - DEFAULT_STRENGTH = 0.1 + DEFAULT_STRENGTH = 0.1 + DEFAULT_BEGINNING_POSITION = 0 - attr_accessor :strength + attr_accessor :samples, + :strength attr_reader :projection def initialize(options = {}) + self.samples = [] self.projection = 0.0 self.strength = options[:strength] || DEFAULT_STRENGTH + + start(:at => DEFAULT_BEGINNING_POSITION) end - def start(_options = {}) + def start(options = {}) self.projection = 0.0 + self.progress = samples[0] = (options[:at] || progress) + end + + def decrement + self.progress -= 1 + end + + def increment + self.progress += 1 + end + + def progress + samples[1] + end + + def progress=(new_progress) + samples[1] = new_progress + calculate(absolute) end - def decrement; end - def increment; end - def progress=(_new_progress); end def total=(_new_total); end def reset - start + start(:at => samples[0]) end def calculate(new_value) @@ -44,6 +64,12 @@ def self.calculate(current_projection, new_value, rate) protected attr_writer :projection + + private + + def absolute + samples[1] - samples[0] + end end end end diff --git a/lib/ruby-progressbar/progress.rb b/lib/ruby-progressbar/progress.rb index a5faba3..5d66176 100644 --- a/lib/ruby-progressbar/progress.rb +++ b/lib/ruby-progressbar/progress.rb @@ -62,7 +62,6 @@ def progress=(new_progress) end @progress = new_progress - running_average_calculator.calculate(absolute) end def running_average diff --git a/spec/lib/ruby-progressbar/calculators/smoothed_average_spec.rb b/spec/lib/ruby-progressbar/calculators/smoothed_average_spec.rb index cccdbfa..6d7264c 100644 --- a/spec/lib/ruby-progressbar/calculators/smoothed_average_spec.rb +++ b/spec/lib/ruby-progressbar/calculators/smoothed_average_spec.rb @@ -41,6 +41,19 @@ module Calculators expect(projector.projection).to be 0.0 end + + it 'resets based on the starting position' do + projector = SmoothedAverage.new(:strength => 0.1) + projector.start(:at => 10) + projector.progress = 20 + + expect(projector.projection).not_to be_zero + + projector.reset + projector.progress = 20 + + expect(projector.projection).to be 9.0 + end end describe '#strength' do diff --git a/spec/lib/ruby-progressbar/progress_spec.rb b/spec/lib/ruby-progressbar/progress_spec.rb index b32da5f..c817cd7 100644 --- a/spec/lib/ruby-progressbar/progress_spec.rb +++ b/spec/lib/ruby-progressbar/progress_spec.rb @@ -129,6 +129,7 @@ class ProgressBar expect(progress.running_average).to be_zero + projector.progress += 40 progress.progress += 40 expect(progress.running_average).to eql 36.0