Skip to content

Commit ddd96e9

Browse files
authored
Allow Rack::Locale to match languages with variants (#190)
Allow Rack::Locale to match languages with variants
1 parent 70930e0 commit ddd96e9

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

lib/rack/contrib/locale.rb

+9-2
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,12 @@ def user_preferred_locale(header)
7272

7373
if I18n.enforce_available_locales
7474
locale = locales.reverse.find { |locale| I18n.available_locales.any? { |al| match?(al, locale) } }
75-
if locale
76-
I18n.available_locales.find { |al| match?(al, locale) }
75+
matched_locale = I18n.available_locales.find { |al| match?(al, locale) } if locale
76+
if !locale && !matched_locale
77+
matched_locale = locales.reverse.find { |locale| I18n.available_locales.any? { |al| variant_match?(al, locale) } }
78+
matched_locale = matched_locale[0,2] if matched_locale
7779
end
80+
matched_locale
7881
else
7982
locales.last
8083
end
@@ -83,5 +86,9 @@ def user_preferred_locale(header)
8386
def match?(s1, s2)
8487
s1.to_s.casecmp(s2.to_s) == 0
8588
end
89+
90+
def variant_match?(s1, s2)
91+
s1.to_s.casecmp(s2[0,2].to_s) == 0
92+
end
8693
end
8794
end

test/spec_rack_locale.rb

+4
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,10 @@ def enforce_available_locales(enforce)
7171
_(response_with_languages('en-gb,en-us;q=0.95;en').body).must_equal('en-gb')
7272
end
7373

74+
specify 'should match languages with variants' do
75+
_(response_with_languages('pt;Q=0.9,es-CL').body).must_equal('es')
76+
end
77+
7478
specify 'should skip * if it is followed by other languages' do
7579
_(response_with_languages('*,dk;q=0.5').body).must_equal('dk')
7680
end

0 commit comments

Comments
 (0)