Skip to content

Commit

Permalink
Allow Rack::Locale to match languages with variants (#190)
Browse files Browse the repository at this point in the history
Allow Rack::Locale to match languages with variants
  • Loading branch information
rodrigoassis authored May 10, 2024
1 parent 70930e0 commit ddd96e9
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/rack/contrib/locale.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
4 changes: 4 additions & 0 deletions test/spec_rack_locale.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit ddd96e9

Please sign in to comment.