class FacebookAds::Batch

Attributes

current_batch[RW]
last_api_response[RW]
operations[RW]
session[RW]

Public Class Methods

new() click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 23
def initialize
  @operations = []
end
with_batch() { || ... } click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 72
def with_batch
  new.tap do |current_batch|
    self.current_batch = current_batch
    yield if block_given?
    self.current_batch = nil
  end
end

Public Instance Methods

<<(api_req) click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 27
def <<(api_req)
  @operations << api_req
  @session ||= api_req.session
  api_req
end
batch_args(slice = operations) click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 53
def batch_args(slice = operations)
  {batch: JSON.dump(operations_args(slice))}.merge(files_args)
end
execute() click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 33
def execute
  return [] if operations.empty?
  operations.each_slice(50) do |slice|
    api_response = APIRequest.new(:post, '', session: session, params: batch_args(slice)).execute_now
    self.last_api_response = api_response
    slice.zip(api_response.result).map do |req, res|
      next unless res

      begin
        req.create_response(
            res['code'],
            convert_headers_to_hash(res['headers']),
            res['body'])
      rescue APIError => e
        e
      end
    end
  end
end
files_args() click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 63
def files_args
  operations.map do |api_req|
    api_req.files
  end.reduce(&:merge)
end
operations_args(slice) click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 57
def operations_args(slice)
  slice.map do |api_req|
    api_req.to_batch_params
  end
end

Private Instance Methods

convert_headers_to_hash(headers) click to toggle source
# File lib/facebook_ads/batch_api/batch.rb, line 82
def convert_headers_to_hash(headers)
  Faraday::Utils::Headers.new(
      Hash[headers.map {|h| [h['name'], h['value']]}]
  )
end