From 20170cb4f3418be07bd2e2e72faa9a2bc7f7b384 Mon Sep 17 00:00:00 2001 From: Matt Jankowski Date: Fri, 14 Apr 2017 19:12:39 -0400 Subject: [PATCH] Improve i18n chooser (#1804) * Add locale spec with failing locale plus region check * Use a more accurate locale when supplied by browser headers Previously we were using a matching option which would use the first locale available which matched the locale portion, even if a region was specified. This changes to first try to find an exact match, and then fall back to the region, and then fall back to the default. * Clean up default_locale method --- app/controllers/concerns/localized.rb | 6 +++++- spec/requests/localization_spec.rb | 31 +++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 spec/requests/localization_spec.rb diff --git a/app/controllers/concerns/localized.rb b/app/controllers/concerns/localized.rb index 22bb5b21af..d9a7a7227b 100644 --- a/app/controllers/concerns/localized.rb +++ b/app/controllers/concerns/localized.rb @@ -27,7 +27,11 @@ module Localized def default_locale ENV.fetch('DEFAULT_LOCALE') { - http_accept_language.compatible_language_from(I18n.available_locales) || I18n.default_locale + user_supplied_locale || I18n.default_locale } end + + def user_supplied_locale + http_accept_language.language_region_compatible_from(I18n.available_locales) + end end diff --git a/spec/requests/localization_spec.rb b/spec/requests/localization_spec.rb new file mode 100644 index 0000000000..d1b7bdc1da --- /dev/null +++ b/spec/requests/localization_spec.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true + +require 'rails_helper' + +describe 'Localization' do + it 'uses a specific region when provided' do + headers = { 'Accept-Language' => 'zh-HK' } + + get "/about", headers: headers + expect(response.body).to include( + I18n.t('about.about_mastodon', locale: 'zh-HK') + ) + end + + it 'falls back to a locale when region missing' do + headers = { 'Accept-Language' => 'es-FAKE' } + + get "/about", headers: headers + expect(response.body).to include( + I18n.t('about.about_mastodon', locale: 'es') + ) + end + it 'falls back to english when locale is missing' do + headers = { 'Accept-Language' => '12-FAKE' } + + get "/about", headers: headers + expect(response.body).to include( + I18n.t('about.about_mastodon', locale: 'en') + ) + end +end