Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Setting Globalize locale based on the Accept-Language HTTP Header Field (See related posts)

This code sets the Globalize locale based on the http accept-language header field. Other options are also considered, in order or precedence:

- Explicetely locale set on URL
- Previous language selection (stored on user session)
- Accept-Language field contents
- Default locale

  before_filter :set_locale
  
  def set_locale
    default_locale = 'en-US'
    request_language = request.env['HTTP_ACCEPT_LANGUAGE']
    request_language = request_language.nil? ? nil : request_language[/[^,;]+/]
    
    @locale = params[:locale] || session[:locale] ||
              request_language || default_locale
    session[:locale] = @locale
    begin
      Locale.set @locale
    rescue
      @locale = default_locale
      Locale.set @locale
    end
    
  end

Comments on this post

neeleshs posts on Sep 22, 2007 at 15:52
How does this work in a multi user scenario?
Consider a site which supports English and French. User A clicks on the french version and user B non the English version. On WEBricks, the same runtime is used (unlike CGI where a new interpreter is launched per request). Since Locale.set uses a class variable to store the locale, the locale is the same "across" the application and not for a user session. This means the locales will switch arbitrarily based on who clicks on which language.

Am I missing something? This will work fine for a CGI environment, as a new ruby interpreter is launched per request. In all other cases (fastCGI/mongrel/WEBricks), the same runtime is shared and this may not work.

You need to create an account or log in to post comments to this site.


Related Posts