Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: AdReportRun can't retain id with post insights #151

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,26 @@ batch = FacebookAds::Batch.with_batch do
end
```

## Insights API Asynchronous Jobs

[Insights API Asynchronous Jobs](https://developers.facebook.com/docs/marketing-api/insights/best-practices/#asynchronous) allows you to get insights asynchronously.


```ruby
ad_account = FacebookAds::AdAccount.get("act_#{account_id}", session)

# Generating a job to create report
ad_report_run = ad_account.insights.create(some_params)

# Waiting until the job completed
until ad_report_run.reload! && ad_report_run.async_status == "Job Completed"
sleep 1
end

# Fetching the report
ad_report_run.insights.all
```

## Logging

```ruby
Expand Down
16 changes: 13 additions & 3 deletions lib/facebook_ads/ad_object.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,24 @@ def initialize(attributes, *args)
raise InvalidParameterError, 'Invalid attributes. Must include at least one attribute'
end

update_attributes(attributes)
# assume object with only id in the attributes as not loaded

# is next arg a list of fields?
fields = (args[0].is_a?(Array) || args[0].is_a?(String)) ? args.shift : []
fields = fields.split(',') if fields.is_a?(String)
session = args.shift

if attributes.has_key? "report_run_id"
# NOTE: `POST <AD_OBJECT>/insights` returns `report_run_id` not `id`.
# SEE: https://developers.facebook.com/docs/marketing-api/insights/best-practices/#asynchronous

attributes.merge!({ "id" => attributes["report_run_id"] })
attributes.delete("report_run_id")

fields.delete("report_run_id")
end

update_attributes(attributes)
# assume object with only id in the attributes as not loaded

self.__all_fields = fields + attributes.keys
self.session = session
end
Expand Down