Sha256: 4bdf9c4077b882f588644fbd2e29d97d07f1b5cf10cb334b98b93fda0eba76a5

Contents?: true

Size: 885 Bytes

Versions: 10

Compression:

Stored size: 885 Bytes

Contents

# frozen_string_literal: true

module MetalArchives
  ##
  # Enumerable collection over a paginated resource
  #
  class Collection
    include Enumerable

    ##
    # Construct a new Collection
    #
    # [+proc+]
    #   +Proc+ or +lambda+, called repeatedly when iterating. Should return an array of results (stateful),
    #   should return an empty array when there are no results left.
    #
    def initialize(proc)
      @proc = proc
    end

    ##
    # Calls the given block once for each element, passing that element as a parameter.
    # If no block is given, an Enumerator is returned.
    #
    def each
      return to_enum :each unless block_given?

      loop do
        items = instance_exec(&@proc)

        items.each do |item|
          yield item
        end

        break if items.empty?
      end
    end

    def empty?
      first.nil?
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
metal_archives-3.0.1 lib/metal_archives/collection.rb
metal_archives-3.0.0 lib/metal_archives/collection.rb
metal_archives-2.2.3 lib/metal_archives/collection.rb
metal_archives-2.2.0 lib/metal_archives/utils/collection.rb
metal_archives-2.1.1 lib/metal_archives/utils/collection.rb
metal_archives-2.1.0 lib/metal_archives/utils/collection.rb
metal_archives-2.0.2 lib/metal_archives/utils/collection.rb
metal_archives-2.0.1 lib/metal_archives/utils/collection.rb
metal_archives-2.0.0 lib/metal_archives/utils/collection.rb
metal_archives-1.0.0 lib/metal_archives/utils/collection.rb