# Suggested code for auto finding the client locale

**URL:** <https://www.ruby-forum.com/t/suggested-code-for-auto-finding-the-client-locale/60590>\
**Category:** Rails I18n\
**Created:** [May 15, 2006, 11:20pm UTC](https://www.ruby-forum.com/t/suggested-code-for-auto-finding-the-client-locale/60590 "2006-05-15T23:20:54Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [May 15, 2006, 11:20pm UTC](https://www.ruby-forum.com/t/suggested-code-for-auto-finding-the-client-locale/60590/1 "2006-05-15T23:20:54Z")

</div>

# 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

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [July 4, 2006, 11:43am UTC](https://www.ruby-forum.com/t/suggested-code-for-auto-finding-the-client-locale/60590/2 "2006-07-04T11:43:07Z")

</div>

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](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 –
