1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
|
# frozen_string_literal: true
module Aws
module Resources
class Collection
extend Aws::Deprecations
include Enumerable
# @param [Enumerator<Array>] batches
# @option options [Integer] :limit
# @option options [Integer] :size
# @api private
def initialize(batches, options = {})
@batches = batches
@limit = options[:limit]
@size = options[:size]
end
# @return [Integer,nil]
# Returns the size of this collection if known, returns `nil` when
# an API call is necessary to enumerate items in this collection.
def size
@size
end
alias :length :size
# @deprecated
# @api private
def batches
::Enumerator.new do |y|
batch_enum.each do |batch|
y << self.class.new([batch], size: batch.size)
end
end
end
# @deprecated
# @api private
def [](index)
if @size
@batches[0][index]
else
raise "unable to index into a lazy loaded collection"
end
end
deprecated :[]
# @return [Enumerator<Band>]
def each(&block)
enum = ::Enumerator.new do |y|
batch_enum.each do |batch|
batch.each do |band|
y.yield(band)
end
end
end
enum.each(&block) if block
enum
end
# @param [Integer] count
# @return [Resource, Collection]
def first(count = nil)
if count
items = limit(count).to_a
self.class.new([items], size: items.size)
else
begin
each.next
rescue StopIteration
nil
end
end
end
# Returns a new collection that will enumerate a limited number of items.
#
# collection.limit(10).each do |band|
# # yields at most 10 times
# end
#
# @return [Collection]
# @param [Integer] limit
def limit(limit)
Collection.new(@batches, limit: limit)
end
private
def batch_enum
case @limit
when 0 then []
when nil then non_empty_batches
else limited_batches
end
end
def non_empty_batches
::Enumerator.new do |y|
@batches.each do |batch|
y.yield(batch) if batch.size > 0
end
end
end
def limited_batches
::Enumerator.new do |y|
yielded = 0
@batches.each do |batch|
batch = batch.take(@limit - yielded)
if batch.size > 0
y.yield(batch)
yielded += batch.size
end
break if yielded == @limit
end
end
end
end
end
end
|