Skip to content
This repository


Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Rails, timezone from GeoIP, locale from request header or parameter sample

branch: master

Fetching latest commit…


Cannot retrieve the latest commit at this time

Octocat-spinner-32 app
Octocat-spinner-32 config
Octocat-spinner-32 db
Octocat-spinner-32 doc
Octocat-spinner-32 lib
Octocat-spinner-32 log
Octocat-spinner-32 public
Octocat-spinner-32 script first commit February 24, 2012
Octocat-spinner-32 test
Octocat-spinner-32 vendor first commit February 24, 2012
Octocat-spinner-32 .DS_Store
Octocat-spinner-32 .gitignore
Octocat-spinner-32 Gemfile
Octocat-spinner-32 Gemfile.lock
Octocat-spinner-32 README.rdoc
Octocat-spinner-32 Rakefile
Octocat-spinner-32 first commit February 24, 2012

Rails, timezone from GeoIP, locale from request header or parameter sample

Guessing timezone from ip

Used geoip gem, with GeoLite Country. ip => country, country => timezone(s). This is done only once when user is registrating for the first time. So, assuming GeoIP.dat file is under /lib/data, inside devise registration form:

<% country ='lib','data','GeoIP.dat')).country(request.remote_ip) %>
<%= f.time_zone_select :time_zone, (country.ip == "") ? nil : TZInfo::Country.get(country.country_code2).zones %>


First, look if params exists (user may require any different locale, for any time, for any reason), next, check if current_user exists, if so, use its settings, if its public user, that try to guess from browser header, and finally set locale from default locale.

I18n.locale = params[:locale] || current_user.try(:locale) || extract_locale_from_accept_language_header
def extract_locale_from_accept_language_header
  request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[en|tr]{2}/).first || I18n.default_locale

Locale scope in routes

Dynamic scope for locales

scope "(:locale)", :locale => /en|tr/ do
  devise_for :users
  root :to => "main#index"

Set locale parameter if it exists in url

def default_url_options(options={})  
  { :locale => I18n.locale }

Update me!

Something went wrong with that request. Please try again.