Rails I8n: Use default locale when the requested locale (from HTTP header) is not available?
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_LA开发者_如何学运维NGUAGE'].scan(/^[a-z]{2}/).first
end
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.
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
精彩评论