hyperrjas hyperrjas - 1 month ago 16
Ruby Question

extract browser language rails 3

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

Answer

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.

Comments