Sha256: e500c19c8739bc1fd1bf4437bdde4e1b84f967c318807923082636495b41aa65

Contents?: true

Size: 1006 Bytes

Versions: 7

Compression:

Stored size: 1006 Bytes

Contents

module Rmega
  class Progress

    def initialize(params)
      @total = params[:total]
      @caption = params[:caption]
      @bytes = 0
      @start_time = Time.now

      show
    end

    def show
      percentage = (100.0 * @bytes / @total).round(2)

      message = "[#{@caption}] #{humanize(@bytes)} of #{humanize(@total)}"

      if ended?
        message << ". Completed in #{elapsed_time} sec.\n"
      else
        message << " (#{percentage}%)"
      end

      blank_line = ' ' * (message.size + 15)
      print "\r#{blank_line}\r#{message}"
    end

    def elapsed_time
      (Time.now - @start_time).round(2)
    end

    def ended?
      @total == @bytes
    end

    def increment(bytes)
      @bytes += bytes
      show
    end

    def humanize(bytes, round = 2)
      units = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB']
      e = (bytes == 0 ? 0 : Math.log(bytes)) / Math.log(1024)
      value = bytes.to_f / (1024 ** e.floor)

      "#{value.round(round)} #{units[e]}"
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
rmega-0.1.7 lib/rmega/progress.rb
rmega-0.1.6 lib/rmega/progress.rb
rmega-0.1.5 lib/rmega/progress.rb
rmega-0.1.4 lib/rmega/progress.rb
rmega-0.1.3 lib/rmega/progress.rb
rmega-0.1.2 lib/rmega/progress.rb
rmega-0.1.1 lib/rmega/progress.rb