Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consistently return array from bulk lookup, even if translation(s) missing #628

Merged
merged 2 commits into from
Jul 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 16 additions & 10 deletions lib/i18n.rb
Original file line number Diff line number Diff line change
Expand Up @@ -214,18 +214,12 @@ def translate(key = nil, throw: false, raise: false, locale: nil, **options) # T

backend = config.backend

result = catch(:exception) do
if key.is_a?(Array)
key.map { |k| backend.translate(locale, k, options) }
else
backend.translate(locale, key, options)
if key.is_a?(Array)
key.map do |k|
translate_key(k, throw, raise, locale, backend, options)
end
end

if result.is_a?(MissingTranslation)
handle_exception((throw && :throw || raise && :raise), result, locale, key, options)
else
result
translate_key(key, throw, raise, locale, backend, options)
end
end
alias :t :translate
Expand Down Expand Up @@ -364,6 +358,18 @@ def available_locales_initialized?

private

def translate_key(key, throw, raise, locale, backend, options)
result = catch(:exception) do
backend.translate(locale, key, options)
end

if result.is_a?(MissingTranslation)
handle_exception((throw && :throw || raise && :raise), result, locale, key, options)
else
result
end
end

# Any exceptions thrown in translate will be sent to the @@exception_handler
# which can be a Symbol, a Proc or any other Object unless they're forced to
# be raised or thrown (MissingTranslation).
Expand Down
7 changes: 7 additions & 0 deletions test/i18n_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,13 @@ def setup
assert_equal "translation missing: en.bogus", I18n.t(:bogus)
end

test "translate given multiple bogus keys returns an array of error messages" do
assert_equal(
["translation missing: en.bogus", "translation missing: en.also_bogus"],
I18n.t([:bogus, :also_bogus]),
)
end

test "translate given an empty string as a key raises an I18n::ArgumentError" do
assert_raises(I18n::ArgumentError) { I18n.t("") }
end
Expand Down