Reputation: 10744
This method extract browser language and is working fine when the language have 2 letter, es, en, de
...etc.
def extract_locale_from_accept_language_header
browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z]{2}/).try(:first).try(:to_sym)
if I18n.available_locales.include? browser_locale
browser_locale
else
I18n.default_locale
end
end
However is not working when the browser language have 4 letters:
en
en-us
en-gb
en-au
en-ca
zh-TW
zh-cn
How can fix this problem?
Thanks
Upvotes: 1
Views: 218
Reputation: 1476
Here is a ruby gem which does exactly what you want:
languages = HTTP::Accept::Language.parse("da, en-gb;q=0.8, en;q=0.7")
expect(languages[0].locale).to be == "da"
expect(languages[1].locale).to be == "en-gb"
expect(languages[2].locale).to be == "en"
It has 100% test coverage on a wide range of inputs.
Upvotes: 0
Reputation: 356
Your regular expression is only looking for two letters try this:
browser_locale = request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z-]{2,5}/).try(:first).try(:to_sym)
This will work with two to five character codes with lower case letters or dashes.
This is just a start you may need to refine this regular expression more.
Upvotes: 1