views:

358

answers:

2

Hi: In my Rails ApplicationController I have added the following methods (from rails guide docs) to support I8n based on http accept language header info. Is there a way to check if the requested locale is available and if not, use the 'english' default locale as marked in environment.rb? Otherwise I get "translation missing" when an unknown locale is used.

def set_locale
   logger.debug "* Accept-Language: #{request.env['HTTP_ACCEPT_LANGUAGE']}"
   I18n.locale = extract_locale_from_accept_language_header
   logger.debug "* Locale set to '#{I18n.locale}'"
end  

private

def extract_locale_from_accept_language_header
    request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
end
A: 

In Rails 2.3 you've a available_locales method available in module I18n (calls the same method from the backend, like I18n::Backend::Simple.available_locales).

If you're still on 2.2 you've to implement it yourself. See: http://guides.rubyonrails.org/i18n.html

Matt
I found that just at the same second ;) See my answer above.
Sney
+1  A: 

What I've done by now is (feel free to comment and post a more rubyish version ;o) ):

def set_locale
  if (I18n.available_locales.any?{|loc| loc.to_s == extract_locale_from_accept_language_header})
  I18n.locale = extract_locale_from_accept_language_header
  end
end  

The new locale is now only set when it is available. My default locale in environment.rb is :en.

Sney