Sha256: 4d57c6b7659db0162df38e79cf8905501ee2ae1d353bb561b3636f82bf7deecd

Contents?: true

Size: 1.23 KB

Versions: 6

Compression:

Stored size: 1.23 KB

Contents

module Killbill
  module Plugin
    module ActiveMerchant
      module ActiveRecord
        require 'active_record'

        # Closest from a streaming API as we can get with ActiveRecord
        class StreamyResultSet
          include Enumerable

          def initialize(limit, batch_size = 100, &delegate)
            @limit = limit
            @batch = [batch_size, limit].min
            @delegate = delegate
          end

          def each(&block)
            (0..(@limit - @batch)).step(@batch) do |i|
              result = @delegate.call(i, @batch)
              block.call(result)
              # Optimization: bail out if no more results
              break if result.nil? || result.empty?
            end if @batch > 0
          ensure
            # Make sure to return DB connections to the Pool
            close_connection
          end

          def to_a
            super.to_a.flatten
          end

          private

          def close_connection
            pool = ::ActiveRecord::Base.connection_pool
            return unless pool.active_connection?

            connection = ::ActiveRecord::Base.connection
            pool.remove(connection)
            connection.disconnect!
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
killbill-3.2.4 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb
killbill-3.2.3 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb
killbill-3.2.2 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb
killbill-3.2.1 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb
killbill-3.2.0 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb
killbill-3.1.12 lib/killbill/helpers/active_merchant/active_record/models/streamy_result_set.rb