Class: Adapi::Keyword

Inherits:
AdGroupCriterion show all
Defined in:
lib/adapi/keyword.rb

Constant Summary

Constants inherited from AdGroupCriterion

AdGroupCriterion::ATTRIBUTES

Constants inherited from Api

Api::API_EXCEPTIONS, Api::LOGGER

Instance Attribute Summary collapse

Attributes inherited from Api

#adwords, #id, #params, #service, #status, #version, #xsi_type

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from AdGroupCriterion

#delete

Methods inherited from Api

#[], #[]=, #check_for_errors, create, #mutate, #new?, #persisted?, #store_errors, to_micro_units, #to_param, update

Constructor Details

#initialize(params = {}) ⇒ Keyword

Returns a new instance of Keyword.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/adapi/keyword.rb', line 27

def initialize(params = {})
  params[:service_name] = :AdGroupCriterionService

  @xsi_type = 'AdGroupCriterion'

  %w{ keywords }.each do |param_name|
    self.send "#{param_name}=", params[param_name.to_sym]
  end

  self.keywords ||= []
  self.keywords.map! { |k| Keyword.keyword_attributes(k) }

  super(params)
end

Instance Attribute Details

#keywordsObject

Returns the value of attribute keywords.



21
22
23
# File 'lib/adapi/keyword.rb', line 21

def keywords
  @keywords
end

Class Method Details

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

Raises:

  • (ArgumentError)


108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/adapi/keyword.rb', line 108

def self.find(amount = :all, params = {})
  params[:format] ||= :google # default, don't do anything with the data from google
  
  params.symbolize_keys!
  # this has no effect, it's here just to have the same interface everywhere
  first_only = (amount.to_sym == :first)

  # we need ad_group_id
  raise ArgumentError, "AdGroup ID is required" unless params[:ad_group_id]
 
  # basic predicates for searching keywords - both are required
  predicates = [
    { :field => 'CriteriaType', :operator => 'EQUALS', :values => [ 'KEYWORD' ] },
    { :field => 'AdGroupId', :operator => 'EQUALS', :values => [ params[:ad_group_id] ] }
  ]
  # supported parameters: id
  predicates += [ :id ].map do |param_name|
    if params[param_name]
      {:field => param_name.to_s.camelcase, :operator => 'EQUALS', :values => params[param_name] }
    end
  end.compact

  # Get all the criteria for this ad group.
  selector = {
    :fields => ['Id', 'CriteriaType', 'KeywordText'],
    :ordering => [{ :field => 'AdGroupId', :sort_order => 'ASCENDING' }],
    :predicates => predicates
    # obsolete, not needed in newer versions of AdWords API 
    # :paging => { :start_index => 0, :number_results => 10 }
  }

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

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

# for now, always return keywords in :google format
=begin
  response = case params[:format].to_sym
  when :short
    Keyword.shortened(response)
  when :params
    Keyword.parameterized(response)
  else
    response
  end
=end

  Keyword.new(
    :ad_group_id => params[:ad_group_id],
    :keywords => response
  )
end

.keyword_attributes(keyword) ⇒ Object

Converts keyword specification from shortened form to Google format



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/adapi/keyword.rb', line 44

def self.keyword_attributes(keyword)
  # detect match type
  match_type = case keyword[0]
  when '"'
    keyword = keyword.slice(1, (keyword.size - 2))
    'PHRASE'
  when '['
    keyword = keyword.slice(1, (keyword.size - 2))
    'EXACT'
  else
    'BROAD'
  end

  # sets whether keyword is negative or not
  negative = if (keyword =~ /^\-/)
    keyword.slice!(0, 1)
    true
  else
    false
  end

  { :text => keyword, :match_type => match_type, :negative => negative }
end

.parameterized(google_keywords = []) ⇒ Object

Converts list of keywords from Google format to params format (the way it can be entered into Keywords model)



185
186
187
188
189
190
191
192
193
194
195
# File 'lib/adapi/keyword.rb', line 185

def self.parameterized(google_keywords = [])
  google_keywords.map do |keyword|        
    kw = keyword[:text][:criterion]
    
    {
      :text => kw[:text],
      :match_type => kw[:match_type],
      :negative => (keyword[:text][:xsi_type] == "NegativeAdGroupCriterion")
    }
  end
end

.shortened(google_keywords = []) ⇒ Object

Converts list of keywords from Google format to short format



167
168
169
170
171
172
173
174
175
176
177
178
179
180
# File 'lib/adapi/keyword.rb', line 167

def self.shortened(google_keywords = [])
  self.parameterized(google_keywords).map do |keyword|
    keyword[:text] = "-%s" % keyword[:text] if keyword[:negative]
    
    case keyword[:match_type]
    when 'PHRASE'
      "\"%s\"" % keyword[:text]
    when 'EXACT'
      "[%s]" % keyword[:text]
    else # 'BROAD'
      keyword[:text]
    end
  end
end

Instance Method Details

#attributesObject



23
24
25
# File 'lib/adapi/keyword.rb', line 23

def attributes
  super.merge( keywords: keywords )
end

#createObject



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/adapi/keyword.rb', line 69

def create
  operations = @keywords.map do |keyword|
    {
      :operator => 'ADD', 
      :operand => {
        :xsi_type => (keyword[:negative] ? 'NegativeAdGroupCriterion' : 'BiddableAdGroupCriterion'),
        :ad_group_id => @ad_group_id,
        :criterion => {
          :xsi_type => 'Keyword',
          :text => keyword[:text],
          :match_type => keyword[:match_type]
        }
      }
    }
  end

  response = self.mutate(operations)

  # check for PolicyViolationErrors, set exemptions and try again
  # do it only once. from my experience with AdWords API, multiple retries are bad practice
  if self.errors[:PolicyViolationError].any?

    self.errors[:PolicyViolationError].each do |e|
      i = e.delete(:operation_index) 
      operations[i][:exemption_requests] = [ { :key => e } ]
    end

    self.errors.clear

    response = self.mutate(operations)
  end

  return false if self.errors.any?
  
  self.keywords = response[:value].map { |keyword| keyword[:criterion] }

  true
end