Sha256: a43e671871a12fb3aa3ac7331bb871b6261f8109ddb618811a948aa574b5fe26

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# encoding: UTF-8

module ProgressReporters

  class ProgressReporter
    DEFAULT_STEP = 1

    attr_reader :step, :last_count, :on_progress_proc, :on_complete_proc

    protected :on_progress_proc
    protected :on_complete_proc

    def initialize
      @step = DEFAULT_STEP
      reset
    end

    def on_progress(&block)
      @on_progress_proc = block
      self
    end

    def on_complete(&block)
      @on_complete_proc = block
      self
    end

    def set_step(step)
      @step = step
      self
    end

    def report_progress(count, total)
      if on_progress_proc
        notify_of_progress(count, total) if count % step == 0
      end

      @last_count = count
    end

    def report_complete
      if on_complete_proc
        notify_of_completion
      end
    end

    def reset
      @last_count = 0
    end

    protected

    # this won't get called if on_progress_proc is nil
    def notify_of_progress(count, total)
      on_progress_proc.call(
        count, total, percentage(count, total)
      )
    end

    # this won't get called if on_complete_proc is nil
    def notify_of_completion
      on_complete_proc.call
    end

    private

    def percentage(count, total, precision = 0)
      if total > 0
        ((count.to_f / total.to_f) * 100).round(precision)
      else
        0
      end
    end
  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
progress-reporters-1.0.0 lib/progress-reporters/progress_reporter.rb