Skip to content

Commit aabf170

Browse files
committed
Merge branch '14-set-available-locales' of git://github.com/pacoguzman/rack-contrib into GH118
2 parents 1a5147c + 0f75e75 commit aabf170

File tree

3 files changed

+29
-3
lines changed

3 files changed

+29
-3
lines changed

lib/rack/contrib/locale.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,13 @@ def accept_locale(env)
3434

3535
lang = languages_and_qvalues.sort_by { |(locale, qvalue)|
3636
qvalue.to_f
37-
}.last.first
37+
}.reverse.detect { |(locale, qvalue)|
38+
if I18n.enforce_available_locales
39+
locale == '*' || I18n.available_locales.include?(locale.to_sym)
40+
else
41+
true
42+
end
43+
}.first
3844

3945
lang == '*' ? nil : lang
4046
end

test/gemfiles/minimum_versions

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ source 'https://rubygems.org'
77
#
88
gem 'rack', '= 1.4.0'
99
gem 'git-version-bump', '= 0.15.0'
10-
gem 'i18n', '= 0.4.0'
10+
gem 'i18n', '= 0.5.2'
1111
gem 'json', '= 1.8.5'
1212
gem 'minitest', '= 5.6.0'
1313
gem 'minitest-hooks', '= 1.0.0'

test/spec_rack_locale.rb

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,14 @@ def response_with_languages(accept_languages)
2424
Rack::MockRequest.new(app).get('/', { 'HTTP_ACCEPT_LANGUAGE' => accept_languages } )
2525
end
2626

27+
def enforce_available_locales(enforce)
28+
default_enforce = I18n.enforce_available_locales
29+
I18n.enforce_available_locales = enforce
30+
yield
31+
ensure
32+
I18n.enforce_available_locales = default_enforce
33+
end
34+
2735
specify 'should use I18n.default_locale if no languages are requested' do
2836
I18n.default_locale = :zh
2937
response_with_languages(nil).body.must_equal('zh')
@@ -47,14 +55,26 @@ def response_with_languages(accept_languages)
4755
end
4856

4957
specify 'should treat a * as "all other languages"' do
50-
response_with_languages('*,en;q=0.5').body.must_equal( I18n.default_locale.to_s )
58+
response_with_languages('*,en;q=0.5').body.must_equal(I18n.default_locale.to_s)
5159
end
5260

5361
specify 'should reset the I18n locale after the response' do
5462
I18n.locale = :es
5563
response_with_languages('en,de;q=0.8')
5664
I18n.locale.must_equal(:es)
5765
end
66+
67+
specify 'should pick the available language' do
68+
enforce_available_locales(true) do
69+
response_with_languages('ch,en;q=0.9,es;q=0.95').body.must_equal('es')
70+
end
71+
end
72+
73+
specify 'when not enforce should pick the language with the highest qvalue' do
74+
enforce_available_locales(false) do
75+
response_with_languages('ch,en;q=0.9').body.must_equal('ch')
76+
end
77+
end
5878
end
5979
rescue LoadError
6080
STDERR.puts "WARN: Skipping Rack::Locale tests (i18n not installed)"

0 commit comments

Comments
 (0)