If you read my last post you’ll know that I’m moving from google ads to banner ads for affiliate programs run by online retailers. But most retailers only target a single country. Showing ads for an American store to visitors from the UK would simply be a waste of ad space.
So I needed some way to target the ads to the visitors country. Enter geocoding. Using one of a number of online services which will take the visitors IP address and return a two letter country code for them.
In Rails there’s a handy gem which can do this, GeoKit. For IP to country coding it can use one of two services, both of which are free: hostip.info and geoplugin.com.
In Rails the process goes as follows: Firstly install the GeoKit gem:
config.gem 'geokit'
In the application.rb file for the application controller, add the following before_filter:
before_filter :get_geo_locNow you’re ready to create the before filter which will run before every page request. Since you don’t want to be hitting the third party servers for every request you will want to store the result of the loop-up in a cookie (in this case called geo-country).
I’ve also added the ability to send a country code with a request for testing purposes. I do this by adding a ?geo=ID to the end of a URL (replacing ID with a country code).
Testing showed one more fix was needed. GeoKit uses one of two services by default with fail over between the two. I found that one was returning the code ‘GB’ for the United Kingdom, the other was returning ‘UK’, so I added a quick fix to convert between the two.
The finished code follows:
def get_geo_loc cookie = true if params['geo'] @geo_country = params['geo'] cookie = false elsif cookies['geo_country'] @geo_country = cookies['geo_country'] else @geo_country = GeoKit::Geocoders::IpGeocoder.do_geocode(request.remote_ip).country_code @geo_country = 'GB' if @geo_country == 'UK' end if cookie cookies['geo_country'] = {:value => @geo_country, :expire =>; 30.days.from_now} else cookies.delete 'geo_country' end end
If you want to see the banners in action and you’re from the US or UK, just visit http://plantality.com, if not click on http://plantality.com?geo=GB or http://plantality.com?geo=US for the USA (note at the time of writing I’ve only created ads for the UK, US ads will be added shortly).
