Sha256: f9313518a0478d4c70953d5ae90fe08a165b98f04d599ed6249877ec6af79010

Contents?: true

Size: 1.39 KB

Versions: 18

Compression:

Stored size: 1.39 KB

Contents

module Frodo
  class Query
    module InBatches
      DEFAULT_BATCH_SIZE = 10

      # Process results in batches.
      #
      # When a block is given, yields `Frodo::Query::Result`
      # objects of specified batch size to the block.
      #
      #   service['Products'].query.in_batches(of: 10) do |batch|
      #     batch.count # batch size (10 except for last batch)
      #     batch.is_a? Frodo::Query::Result # true
      #   end
      #
      # Returns an Enumerator to process results individually.
      #
      #   service['Products'].query.in_batches.each do |entity|
      #     entity.is_a? Frodo::Entity # true
      #   end
      #
      # @param of: [int] batch size
      # @return [Enumerator]
      def in_batches(of: DEFAULT_BATCH_SIZE, &block)
        per_page = of

        if block_given?
          each_batch(of, &block)
        else
          Enumerator.new do |result|
            each_batch(of) do |batch|
              batch.each { |entity| result << entity }
            end
          end
        end
      end

      private

      def each_batch(per_page, &block)
        page = 0

        loop do
          batch = get_paginated_entities(per_page, page)
          break if batch.empty?

          yield batch

          page += 1
        end
      end

      def get_paginated_entities(per_page, page)
        skip(per_page * page).limit(per_page).execute
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
frodo-0.12.8 lib/frodo/query/in_batches.rb
frodo-0.12.7 lib/frodo/query/in_batches.rb
frodo-0.12.6 lib/frodo/query/in_batches.rb
frodo-0.12.5 lib/frodo/query/in_batches.rb
frodo-0.12.4 lib/frodo/query/in_batches.rb
frodo-0.12.2 lib/frodo/query/in_batches.rb
frodo-0.12.1 lib/frodo/query/in_batches.rb
frodo-0.12.0 lib/frodo/query/in_batches.rb
frodo-0.11.0 lib/frodo/query/in_batches.rb
frodo-0.10.8 lib/frodo/query/in_batches.rb
frodo-0.10.7 lib/frodo/query/in_batches.rb
frodo-0.10.6 lib/frodo/query/in_batches.rb
frodo-0.10.5 lib/frodo/query/in_batches.rb
frodo-0.10.4 lib/frodo/query/in_batches.rb
frodo-0.10.3 lib/frodo/query/in_batches.rb
frodo-0.10.2 lib/frodo/query/in_batches.rb
frodo-0.10.1 lib/frodo/query/in_batches.rb
frodo-0.10.0 lib/frodo/query/in_batches.rb