Class: FacebookAds::Batch

Inherits:
Object
  • Object
show all
Defined in:
lib/facebook_ads/batch_api/batch.rb

Class Attribute Summary collapse

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBatch

Returns a new instance of Batch.



11
12
13
# File 'lib/facebook_ads/batch_api/batch.rb', line 11

def initialize
  @operations = []
end

Class Attribute Details

.current_batchObject

Returns the value of attribute current_batch.



58
59
60
# File 'lib/facebook_ads/batch_api/batch.rb', line 58

def current_batch
  @current_batch
end

Instance Attribute Details

#last_api_responseObject

Returns the value of attribute last_api_response.



9
10
11
# File 'lib/facebook_ads/batch_api/batch.rb', line 9

def last_api_response
  @last_api_response
end

#operationsObject

Returns the value of attribute operations.



9
10
11
# File 'lib/facebook_ads/batch_api/batch.rb', line 9

def operations
  @operations
end

#sessionObject

Returns the value of attribute session.



9
10
11
# File 'lib/facebook_ads/batch_api/batch.rb', line 9

def session
  @session
end

Class Method Details

.with_batchObject



60
61
62
63
64
65
66
# File 'lib/facebook_ads/batch_api/batch.rb', line 60

def with_batch
  new.tap do |current_batch|
    self.current_batch = current_batch
    yield if block_given?
    self.current_batch = nil
  end
end

Instance Method Details

#<<(api_req) ⇒ Object



15
16
17
18
19
# File 'lib/facebook_ads/batch_api/batch.rb', line 15

def <<(api_req)
  @operations << api_req
  @session ||= api_req.session
  api_req
end

#batch_args(slice = operations) ⇒ Object



41
42
43
# File 'lib/facebook_ads/batch_api/batch.rb', line 41

def batch_args(slice = operations)
  {batch: JSON.dump(operations_args(slice))}.merge(files_args)
end

#executeObject



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/facebook_ads/batch_api/batch.rb', line 21

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_argsObject



51
52
53
54
55
# File 'lib/facebook_ads/batch_api/batch.rb', line 51

def files_args
  operations.map do |api_req|
    api_req.files
  end.reduce(&:merge)
end

#operations_args(slice) ⇒ Object



45
46
47
48
49
# File 'lib/facebook_ads/batch_api/batch.rb', line 45

def operations_args(slice)
  slice.map do |api_req|
    api_req.to_batch_params
  end
end