diff --git a/README.md b/README.md index f056d69f..d1a76bd1 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/lib/facebook_ads/ad_object.rb b/lib/facebook_ads/ad_object.rb index a25fa749..2cc475e2 100644 --- a/lib/facebook_ads/ad_object.rb +++ b/lib/facebook_ads/ad_object.rb @@ -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 /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