From ddd96e9343417bb810bf96620cae609b920c8c3d Mon Sep 17 00:00:00 2001 From: Rodrigo Assis <1258016+rodrigoassis@users.noreply.github.com> Date: Fri, 10 May 2024 05:36:07 -0300 Subject: [PATCH] Allow Rack::Locale to match languages with variants (#190) Allow Rack::Locale to match languages with variants --- lib/rack/contrib/locale.rb | 11 +++++++++-- test/spec_rack_locale.rb | 4 ++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/lib/rack/contrib/locale.rb b/lib/rack/contrib/locale.rb index 167bf907..0dbccc29 100644 --- a/lib/rack/contrib/locale.rb +++ b/lib/rack/contrib/locale.rb @@ -72,9 +72,12 @@ def user_preferred_locale(header) if I18n.enforce_available_locales locale = locales.reverse.find { |locale| I18n.available_locales.any? { |al| match?(al, locale) } } - if locale - I18n.available_locales.find { |al| match?(al, locale) } + matched_locale = I18n.available_locales.find { |al| match?(al, locale) } if locale + if !locale && !matched_locale + matched_locale = locales.reverse.find { |locale| I18n.available_locales.any? { |al| variant_match?(al, locale) } } + matched_locale = matched_locale[0,2] if matched_locale end + matched_locale else locales.last end @@ -83,5 +86,9 @@ def user_preferred_locale(header) def match?(s1, s2) s1.to_s.casecmp(s2.to_s) == 0 end + + def variant_match?(s1, s2) + s1.to_s.casecmp(s2[0,2].to_s) == 0 + end end end diff --git a/test/spec_rack_locale.rb b/test/spec_rack_locale.rb index c8e5c173..2bdfbd8f 100644 --- a/test/spec_rack_locale.rb +++ b/test/spec_rack_locale.rb @@ -71,6 +71,10 @@ def enforce_available_locales(enforce) _(response_with_languages('en-gb,en-us;q=0.95;en').body).must_equal('en-gb') end + specify 'should match languages with variants' do + _(response_with_languages('pt;Q=0.9,es-CL').body).must_equal('es') + end + specify 'should skip * if it is followed by other languages' do _(response_with_languages('*,dk;q=0.5').body).must_equal('dk') end