Method: Adapi::Campaign.find

Defined in:
lib/adapi/campaign.rb

.find(amount = :all, params = {}) ⇒ Object

Searches for campaign/s according to given parameters

Input parameters are dynamic. Special case: single number or string on input is considered to be id and we want to search for a single campaign by id



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/adapi/campaign.rb', line 340

def self.find(amount = :all, params = {})
  # find single campaign by id
  if params.empty? and not amount.is_a?(Symbol)
    params[:id] = amount.to_i
    amount = :first
  end

  params.symbolize_keys!
  first_only = (amount.to_sym == :first)

  predicates = [ :id ].map do |param_name|
    if params[param_name]
      # convert to array
      value = Array.try_convert(params[param_name]) ? params_param_name : [params[param_name]]
      { field: param_name.to_s.camelcase, operator: 'IN', values: value }
    end
  end.compact

  # TODO make configurable (but for the moment, return everything)
  select_fields = %w{ Id Name Status ServingStatus 
    StartDate EndDate AdServingOptimizationStatus } 
  # retrieve CampaignStats fields
  select_fields += %w{ Clicks Impressions Cost Ctr }
  # retrieve Budget fields
  select_fields += %w{ Amount Period DeliveryMethod } 
  # retrieve BiddingStrategy fields
  select_fields += %w{ BiddingStrategy BidCeiling EnhancedCpcEnabled }
  # retrieve NetworkSetting fields
  select_fields += NETWORK_SETTING_KEYS.map { |k| k.to_s.camelize } 

  selector = {
    :fields => select_fields,
    :ordering => [ { field: 'Name', sort_order: 'ASCENDING' } ],
    :predicates => predicates
  }

  response = Campaign.new.service.get(selector)

  response = (response and response[:entries]) ? response[:entries] : []

  response.map! do |campaign_data|
    campaign = Campaign.new(campaign_data)
    # TODO allow mass assignment of :id
    campaign.id = campaign_data[:id]
    campaign
  end

  first_only ? response.first : response
end