Sha256: 57643ae70d225e3d3af9673dfeb7c8fb6dc76c7a5e29ce461804dfe83e45a7b8

Contents?: true

Size: 1.48 KB

Versions: 1

Compression:

Stored size: 1.48 KB

Contents

module SoapyCake
  class AdminBatched
    class BatchedRequest
      # Both 0 and 1 return the first element. We need to set it to 1,
      # otherwise we get an overlap in the next call. This is not documented in the API spec.
      INITIAL_OFFSET = 1

      # This value depends on the entity size.
      # When all offers have a lot of info (e.g. geotargeting) we probably need to decrease this.
      LIMIT = 500

      def initialize(admin, method, opts)
        if opts.key?(:row_limit) || opts.key?(:start_at_row)
          fail Error, 'Cannot set row_limit/start_at_row in batched mode!'
        end

        @admin = admin
        @method = method
        @opts = opts
        @offset = INITIAL_OFFSET
        @finished = false
      end

      def to_enum
        Enumerator.new do |y|
          next_batch.each { |row| y << row } until finished
        end
      end

      private

      attr_reader :admin, :method, :opts, :finished, :offset

      def next_batch
        result = admin.public_send(method, opts.merge(row_limit: LIMIT, start_at_row: offset))
        @finished = true if result.count < LIMIT
        @offset += LIMIT
        result
      end
    end

    ALLOWED_METHODS = %i(advertisers affiliates campaigns offers creatives)

    def method_missing(name, opts = {})
      fail Error, "Invalid method #{name}" unless ALLOWED_METHODS.include?(name)

      BatchedRequest.new(admin, name, opts).to_enum
    end

    private

    def admin
      @admin ||= Admin.new
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
soapy_cake-1.11.0 lib/soapy_cake/admin_batched.rb