Rorra's blog Senior Developer

January 10, 2010

Integrating radiant 0.9, globalize and GeoIP

Filed under: Ruby — admin @ 6:28 AM


After downloading and using radiant 0.9 and globalize, I realized that I wanted to redirect the users by default with their geo location.
So I installed GeoIP and then I had to do these little modifications to the Globalize plugin.
First, I edit the file config/environment.rb and added this line, in order to load GeoIP with the application

config.gem 'geoip'

Then I updated the file vendor/extensions/globalize2/lib/globalize2/application_controller_extensions.rb

module Globalize2
  module SiteControllerExtensions
    def self.included(base)
      base.class_eval do
        alias_method_chain :find_page, :globalize

        alias_method_chain :show_page, :homepage_redir
      end
    end

    def show_page_with_homepage_redir
      url = params[:url]
      if Array === url
        url = url.join('/')
      else
        url = url.to_s
      end

      if url == '/'
        locale = params[:locale] || cookies[:locale] || session[:locale] || Globalize2Extension.ip_lookup(request.remote_ip)
        redirect_to CGI.unescape('/' + locale + '/') and return
      end

      show_page_without_homepage_redir
    end

    def find_page_with_globalize(url)
      globalized_url = '/' + I18n.locale + '/' + url
      find_page_without_globalize(globalized_url)
    end
  end
end

So, as you can see on the code, I also check if the user has the language selected in a cookie, and when the user selects (or get a locale by default), I set the cookie with the locale, so the next time the user came into the site, he will see the last language selected.
Finally, I updated the file vendor/extensions/globalize2/globalize2_extension.rb and added the following method, where I get the country code from the user, and I set the locale based on his country ip, or the default locale.

  def ip_lookup(ip)
    g = GeoIP.new( File.join(File.dirname(__FILE__), '..', '..', 'gems', 'geoip-0.8.6', 'GeoIP.dat'))
    r = g.country(ip)
    country_code = r[3]
    case country_code
      when 'DE'
        'de'
      when 'GB'
        'uk'
      when 'AU'
        'au'
      when 'FR'
        'fr'
      when ' US'
        'us'
      else
        'us'
    end
  end

And finally, we need to tell Radiant to load the GeoIP library, so in the same file, we add

  extension_config do |config|
    config.gem 'geoip', :source => 'http://github.com'
  end

So that’s all, now you have GeoIP working with globalize and Radiant 0.9 :)

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress