Suggested code for auto finding the client locale


#1

Put in your environment.rb :#

----------------------------ENV[‘APP_AVAILABLE_LOCALES’] = /^fr|en|es/ #
suggestion…ENV[‘APP_DEFAULT_LOCALE’] = ‘fr’ # YASuggestion

And in application.rb :# -----------------------

before_filter :set_locale

def set_locale # if user clicked on a link for selecting his locale if
locale = params[:locale].match( ENV[‘APP_AVAILABLE_LOCALES’] )
session[:locale] = locale[0] # or if the locale is already set in the
session elsif session[:locale].match( ENV[‘APP_AVAILABLE_LOCALES’] ) #
or if the browser sends its locale elsif locale =
ENV[‘HTTP_ACCEPT_LANGUAGE’].match(ENV[‘APP_AVAILABLE_LOCALES’] )
session[:locale] = locale[0] # else we’re not lucky else
session[:locale] = ENV[‘APP_DEFAULT_LOCALE’] endend


#2

Another mail on the Globalize mailing list about this topic by Thiago
Arrais, (Globalize flavor this time):

– begin –

Here is the code I came up with:

http://www.textsnippets.com/posts/show/546

It considers not only the accept-language field, but other user options.
In order of precedence they are:

  • Explicit locale passed on URL
  • Previous language selection (stored on user session)
  • Accept-Language field contents
  • Default locale

You may package this snippet with Globalize in any way you’d like.

Cheers,

Thiago A.

– end –