Sha256: 62f8b41a3ff2b4fab148c37f47e607dc18a3a2f6a9c5a9175d0f4bf839cfd7d6

Contents?: true

Size: 1.28 KB

Versions: 19

Compression:

Stored size: 1.28 KB

Contents

module Braintree
  class ResourceCollection # :nodoc:
    include Enumerable

    attr_reader :ids

    def initialize(response, &block) # :nodoc:
      @ids = Util.extract_attribute_as_array(response[:search_results], :ids)
      @page_size = response[:search_results][:page_size]
      @paging_block = block
    end

    # Yields each item
    def each(&block)
      @ids.each_slice(@page_size) do |page_of_ids|
        resources = @paging_block.call(page_of_ids)
        resources.each(&block)
      end
    end

    def empty?
      @ids.empty?
    end

    # Returns the first or the first N items in the collection or nil if the collection is empty
    def first(amount = 1)
      return nil if @ids.empty?
      return @paging_block.call([@ids.first]).first if amount == 1

      @ids.first(amount).each_slice(@page_size).flat_map do |page_of_ids|
        @paging_block.call(page_of_ids)
      end
    end

    # Only the maximum size of a resource collection can be determined since the data on the server can change while
    # fetching blocks of results for iteration.  For example, customers can be deleted while iterating, so the number
    # of results iterated over may be less than the maximum_size.  In general, this method should be avoided.
    def maximum_size
      @ids.size
    end
  end
end

Version data entries

19 entries across 19 versions & 1 rubygems

Version Path
braintree-4.15.0 lib/braintree/resource_collection.rb
braintree-4.14.0 lib/braintree/resource_collection.rb
braintree-4.13.0 lib/braintree/resource_collection.rb
braintree-4.12.0 lib/braintree/resource_collection.rb
braintree-4.11.0 lib/braintree/resource_collection.rb
braintree-4.10.0 lib/braintree/resource_collection.rb
braintree-4.9.0 lib/braintree/resource_collection.rb
braintree-4.8.0 lib/braintree/resource_collection.rb
braintree-4.7.0 lib/braintree/resource_collection.rb
braintree-4.6.0 lib/braintree/resource_collection.rb
braintree-4.5.0 lib/braintree/resource_collection.rb
braintree-4.4.0 lib/braintree/resource_collection.rb
braintree-4.3.0 lib/braintree/resource_collection.rb
braintree-4.2.0 lib/braintree/resource_collection.rb
braintree-4.1.0 lib/braintree/resource_collection.rb
braintree-4.0.0 lib/braintree/resource_collection.rb
braintree-3.4.0 lib/braintree/resource_collection.rb
braintree-3.3.0 lib/braintree/resource_collection.rb
braintree-3.2.0 lib/braintree/resource_collection.rb