Module: AdMob

Defined in:
lib/admob.rb

Overview

This module encapsulates functionality (ad requests, analytics requests) provided by AdMob. See README.txt for usage.

Defined Under Namespace

Classes: Defaults, Error

Constant Summary collapse

GEM_VERSION =
'1.1.2'
ENDPOINT =
URI.parse('http://r.admob.com/ad_source.php')
PUBCODE_VERSION =
'20090714-RUBY-8708a7ab5f2b70b6'
DEFAULT_TIMEOUT =
1.0

Class Method Summary collapse

Class Method Details

.config {|AdMob::Defaults| ... } ⇒ Object

Provides access to AdMob config, used for setting default request info. Currently, can be used to set defaults for: publisher_id, analytics_id, ad encoding, request timeout, cookie_domain, cookie_path and whether exceptions are raised when something goes wrong. For example, in environment.rb:

require 'admob'
AdMob::config do |c|
  c.publisher_id = 'YOUR_DEFAULT_PUBLISHER_ID'
  c.analytics_id = 'YOUR_DEFAULT_ANALYTICS_ID'
  c.encoding = 'SJIS'
  c.timeout = 3
  c.raise_exceptions = true
  c.cookie_domain = 'example.com' # this can also be passed to AdMob::set_cookie() but not AdMob::request()
  c.cookie_path = '/' # this can also be passed to AdMob::set_cookie() but not AdMob:request()
end

Yields:



149
150
151
# File 'lib/admob.rb', line 149

def self.config
  yield AdMob::Defaults
end

.request(request, session_id, params = {}) ⇒ Object

Make an AdMob ad/analytics request. The first param is the request variable from Rails; the second is a unique session identifier. In general, requests should always be of the form <%= AdMob::request(request, session.session_id, ...) %>. Regardless of how many times AdMob::request is called, only one analytics call will be made per page load. The remaining params set optional features of the request. Params that can be set are:

:publisher_id

your admob publisher_id, a default can be set using AdMob::config {|c| c.publisher_id = "YOUR_PUBLISHER_ID"}

:analytics_id

your admob analytics_id, a default can be set using AdMob::config {|c| c.analytics_id = "YOUR_ANALYTICS_ID"}

:ad_request

whether to make an ad request, defaults to true

:analytics_request

whether to make an analytics request, defaults to true

:encoding

char encoding of the response, either “UTF-8” or “SJIS”, defaults to UTF-8

:markup

your site’s markup, e.g. “xhtml”, “wml”, “chtml”

:postal_code

postal code of the current user, e.g. “94401”

:area_code

area code of the current user, e.g. “415”

:coordinates

lat/long of the current user, comma separated, e.g. “37.563657,-122.324807”

:dob

date of birth of the current user, e.g. “19800229”

:gender

gender of the current user, e.g. “m” or “f”

:keywords

keywords, e.g. “ruby gem admob”

:search

searchwords (much more restrictive than keywords), e.g. “ruby gem admob”

:title

title of the page, e.g. “Home Page”

:event

the event you want to report to analytics, e.g. “reg_success”

:text_only

if set to true, don’t return a banner ad for this request

:test

whether this should issue a test ad request, not a real one

:timeout

override the default timeout value for this ad request in seconds, e.g. 2

:raise_exceptions

whether to raise exceptions when something goes wrong (defaults to false); exceptions will all be instances of AdMob::Error; a default can be set using AdMob::config {|c| c.raise_exceptions = true}



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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
# File 'lib/admob.rb', line 41

def self.request(request, session_id, params = {})
  raise_exceptions = params[:raise_exceptions].nil? ? AdMob::Defaults.raise_exceptions : params[:raise_exceptions]
  
  if raise_exceptions and !params[:cookie_domain].nil?
    raise AdMob::Error.new("Cannot set cookie_domain in AdMob::request(), set the cookie_domain in the call to AdMob::set_cookie()")
  end
  
  if raise_exceptions and !params[:cookie_path].nil?
    raise AdMob::Error.new("Cannot set cookie_path in AdMob::request(), set the cookie_path in the call to AdMob::set_cookie()")
  end
  
  # Build the post request
  post_data = self.build_post_data(request, session_id, params)
  if post_data.nil?
    raise AdMob::Error.new("AdMob::request called as neither an ad nor an analytics request") if raise_exceptions
    return ''
  end
  
  # Send request
  req = Net::HTTP::Post.new(ENDPOINT.path)
  req.set_form_data(post_data)
  conn = Net::HTTP.new(ENDPOINT.host, ENDPOINT.port)
  timeout = params[:timeout] || AdMob::Defaults.timeout || DEFAULT_TIMEOUT
  conn.read_timeout = timeout
  conn.open_timeout = timeout
  begin
    start = Time.now.getutc.to_f
    response = conn.start {|http| http.request(req)}
    contents = response.body
  rescue Timeout::Error => te
    raise AdMob::Error.new("AdMob::request timed out; timeout was #{timeout}, elapsed time was #{Time.now.to_f - post_data['z']}") if raise_exceptions
  rescue
    raise AdMob::Error.new("AdMob::request encountered unexpected exception #{$!}") if raise_exceptions
  ensure
    contents ||= ''
    lt = Time.now.getutc.to_f - start
  end
  
  # If appropriate, add the analytics pixel
  if !request.env['admob_pixel_sent']
    request.env['admob_pixel_sent'] = true
    contents << '<img src="http://p.admob.com/e0?'
    contents << "rt=#{post_data['rt']}&amp;"
    contents << "z=#{post_data['z']}&amp;"
    contents << "a=#{post_data['a']}&amp;"
    contents << "s=#{post_data['s']}&amp;"
    contents << "o=#{post_data['o']}&amp;"
    contents << "lt=%0.4f&amp;" % lt
    contents << "to=#{timeout}"
    contents << '" alt="" width="1" height="1"/>'
  end
  
  contents
end

This function should be called from an ActionController to set a cookie on behalf of AdMob. If you need to override the default cookie domain or cookie path, pass these as optional parameters to AdMob::set_cookie().

AdMob::set_cookie(request, cookies, :cookie_domain => 'example.com', :cookie_path => '/videos')

You can NOT pass cookie_domain or cookie_path as optional parameters to AdMob::request() AdMob recommends using a before_filter in your ActionController::Base class (usually in app/controllers/application.rb) to call set_cookie on each request. Here is a sample application.rb.

require 'admob'
# Filters added to this controller apply to all controllers in the application.
# Likewise, all the methods added will be available for all controllers.

class ApplicationController < ActionController::Base
  before_filter :admob_set_cookie

  def admob_set_cookie
    AdMob::set_cookie(request, cookies)
  end
end


113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/admob.rb', line 113

def self.set_cookie(request, cookies, params = {})
  # don't make a new cookie if one already exists
  return if request.env['admobuu'] or cookies[:admobuu]
  
  # make a new cookie
  ua = request.user_agent || ''
  value = MD5.hexdigest(rand().to_s + ua + request.remote_ip + Time.now.to_f.to_s)
  new_cookie = { :value    => value,
                 :expires  => Time.at(0x7fffffff), # end of 32 bit time
                 :path     => params[:cookie_path] || AdMob::Defaults.cookie_path || "/" }
  
  domain = params[:cookie_domain] || AdMob::Defaults.cookie_domain
  if domain
    domain = '.' + domain if domain[0].chr != '.'
    new_cookie[:domain] = domain
  end
  cookies[:admobuu] = new_cookie
  
  # make this cookie visible to the current page
  request.env['admobuu'] = value
end