I have the following code that is working to assign a locale based first on a param, then a previously set cookie and then by requesting the HTTP_ACCEPT_LANGUAGE.
def set_locale
if params[:locale]
I18n.locale = params[:locale]
elsif cookies[:locale]
I18n.locale = cookies[:locale]
else
I18n.locale = sanitizeLocale(request.env["HTTP_ACCEPT_LANGUAGE"]) # e.g. "en,es;q=0.8,de-de;q=0.5,en-us;q=0.3"
end
cookies[:locale] = I18n.locale
end
def sanitizeLocale(locale)
@locale, lang_weight = cookies[:locale] || begin
if accept_lang = request.env["HTTP_ACCEPT_LANGUAGE"] # e.g. "en,es;q=0.8,de-de;q=0.5,en-us;q=0.3"
accept_lang.to_s.split(',').collect {|l| x,y = l.split(';q='); [x.split('-').first, (y||1).to_f]}.sort_by(&:last).reverse.find {|lang, lang_weight| %w[es en it fr de].include?(lang)}
# returns ["en", 1.0]
end
end || 'en' # default
return @locale
end
My question is how can I check both the params[:locale] given and cookies[:locale] against the sanitizeLocale. I’m interesting in only get a valid value such as es en it fr de or default to en based on the input.
I been trying to just pass its values to sanitizeLocale similarly I’m doing for HTTP_ACCEPT_LANGUAGE for some reason I can’t understand is not working and is always defaulting to en even when params[:locale] given values are valid like it.
First, we can simplify your Accept-Language parsing a bit:
The
to_swill take care ofnils and the lambdas and extra variables are just there to clarify the logic. You don’t have to do this, all you really need is a method that returns the language codes that are acceptable to both the user and your software ordered by the user’s preference.Now back to
set_locale. You say that you need the language to match Accept-Langauge (with'en'as a fallback) regardless of what the URL or cookies have to say. That means that you have to parse Accept-Language no matter what and then checkparams[:locale]andcookies[:locale]against that list:You could also add a little “I’ve already done all this work” flag to the cookies so that you could simply trust
cookies[:locale]if the flag is set; there’s probably no reason to prematurely optimizeset_localethough.