diff --git a/lib/rack/contrib/locale.rb b/lib/rack/contrib/locale.rb index 167bf90..0dbccc2 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 c8e5c17..2bdfbd8 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