AdMob sample code for Rails

I don’t see any discussion about AdMob, an aggregator for ads for
mobile phones websites. They’re going to live for a bit until AdSense
puts out it’s mobile-capable versions.

AdMob just put up Rails sample code for Rails. I’ve included it below.
It’s pretty simple. Unlike Google AdSense, which requires JavaScript,
this code builds an HTTP request, performs a GET from the AdMob server,
then gets the Ad text back that gets included in the HTML.

I’ve got a couple of questions and comments, hoping to have some other
sets of Rails eyes take a gander:

  1. There are some obvious spots for refactoring. link_to isn’t used,
    for example. And a lot of this could be in helper functions.

  2. That said, it seems like a bad idea to have all this embedded right
    in the RHMTL template for performance. Is that right?

  3. I don’t understand the request.env lines. Will these get the IP &
    the User Agent of the browser making the request? Will that still work
    if it’s in the RHTML? What about a helper function?


require ‘net/http’

editable area

change mob_mode from “test” to “live” when you are done testing

mob_mode = “test”

use this to set a default link to appear if AdMob does not return

an ad
mob_alternate_link = “”

end editable area

User agent and IP: used for ad targeting

mob_ua = url_encode(request.env[“HTTP_USER_AGENT”])
mob_ip = url_encode(request.env[“REMOTE_ADDR”])

mob_m = “”
if mob_mode == “test”
mob_m = “&m”

build the request url

mob_url = “[AdMobKey]&u=” +
mob_ua + “&i=” + mob_ip + mob_m

# make the request
response = Net::HTTP.get_response(URI.parse(mob_url))

  if response.code == '200'
      mob_content = response.body
      # parse result
      if mob_content.include?('><')
          mob_ad_text = mob_content.split('><')[0]
          mob_ad_link = mob_content.split('><')[1]

      if !mob_ad_link.empty?
          # display AdMob Ad
          mob_link = "<a href='" + mob_ad_link + "'>" + mob_ad_text
  • “”
    # no AdMob ad, display alternate
    mob_link = mob_alternate_link
    mob_link = mob_alternate_link

    # no ad or server returned and invalid response code
    # display alternate link
    mob_link = mob_alternate_link

<%= mob_link %>