Sha256: ffd6cc5a8e4ff0e03f04daceacb80b8e6a39dc46b2be28aa6fb1644e709682f3

Contents?: true

Size: 1.1 KB

Versions: 1

Compression:

Stored size: 1.1 KB

Contents

require 'progress'

class Progress
  class WithProgress
    include Enumerable

    # initialize with object responding to each, title and optional length
    # if block is provided, it is passed to each
    def initialize(enumerable, title, length = nil, &block)
      @enumerable, @title, @length = enumerable, title, length
      each(&block) if block
    end

    # each object with progress
    def each
      Progress.start(@title, length) do
        @enumerable.each do |object|
          Progress.step do
            yield object
          end
        end
      end
    end

    # determine number of objects
    def length
      @length ||= if @enumerable.respond_to?(:length) && !@enumerable.is_a?(String)
        @enumerable.length
      elsif @enumerable.respond_to?(:count)
        @enumerable.count
      elsif @enumerable.respond_to?(:to_a)
        @enumerable.to_a.length
      else
        @enumerable.inject(0){ |length, obj| length + 1 }
      end
    end

    # returns self but changes title
    def with_progress(title = nil, &block)
      @title = title
      block ? each(&block) : self
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
progress-2.1.1 lib/progress/with_progress.rb