Skip to content

Commit 336fafa

Browse files
committed
Return translation string if fallback locale is not available
1 parent 100c705 commit 336fafa

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

lib/grape/exceptions/base.rb

+6-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,12 @@ def translate(key, **options)
7474
options = options.dup
7575
options[:default] &&= options[:default].to_s
7676
message = ::I18n.translate(key, **options)
77-
message.present? ? message : ::I18n.translate(key, locale: FALLBACK_LOCALE, **options)
77+
message.present? ? message : fallback_message(key, **options)
78+
end
79+
80+
def fallback_message(key, **options)
81+
return key unless ::I18n.available_locales.include?(FALLBACK_LOCALE)
82+
::I18n.translate(key, locale: FALLBACK_LOCALE, **options)
7883
end
7984
end
8085
end

spec/grape/exceptions/base_spec.rb

+14-5
Original file line numberDiff line numberDiff line change
@@ -9,21 +9,30 @@
99

1010
context 'when I18n enforces available locales' do
1111
before { I18n.enforce_available_locales = true }
12-
after { I18n.enforce_available_locales = false }
12+
after do
13+
I18n.available_locales = %i[de en]
14+
I18n.enforce_available_locales = false
15+
end
1316

1417
context 'when the fallback locale is available' do
15-
before { I18n.available_locales = %i[de en] }
18+
before do
19+
I18n.available_locales = %i[de en]
20+
I18n.default_locale = :de
21+
end
1622

1723
it 'returns the translated message' do
1824
expect(subject).to eq('cannot convert String to xml')
1925
end
2026
end
2127

2228
context 'when the fallback locale is not available' do
23-
before { I18n.available_locales = %i[de jp] }
29+
before do
30+
I18n.available_locales = %i[de jp]
31+
I18n.default_locale = :de
32+
end
2433

25-
it 'currently raises an error' do
26-
expect { subject }.to raise_error(I18n::InvalidLocale)
34+
it 'returns the translation string' do
35+
expect(subject).to eq("grape.errors.messages.#{key}")
2736
end
2837
end
2938
end

0 commit comments

Comments
 (0)