1

I'm attempting to gather some analytics based off of the user's accept-language header. It would be very helpful to turn "en-US,en;q=0.8" into English (United States).

The only way I've really seen is using I18n and putting the name in the yaml file. This doesn't seem like a great solution because I would have to "translate" each possibility. It would make sense if I were using it for taking the user's preferred language and translating the page, but that's a different use case.

Is there any gem/gist I could use to find the language's display name?

Tom Prats
  • 7,364
  • 9
  • 47
  • 77

1 Answers1

1

I would just copy the list of language and country codes from Wikipedia and transfer them into hashes:

LANGUAGE_CODES = {
  aa: 'Afar',
  ab: 'Abkhaz',
  # ...
  zu: 'Zulu'
}

COUNTRY_CODES = {
  AD: 'Andorra',
  AE: 'United Arab Emirates',
  # ...
  ZW: 'Zimbabwe'
}

with this hashes a simple method like the following should be able to extract the language and country information you are interested in:

def language_info(accepted_language)
  language, country = accepted_language.scan(/(\w{2})-(\w{2})/)

  if language && country
    "#{LANGUAGE_CODES[language]} (#{COUNTRY_CODES[country]})"
  end
end

# language_info(request.env['HTTP_ACCEPT_LANGUAGE'])
spickermann
  • 100,941
  • 9
  • 101
  • 131