Skip to content

Commit

Permalink
Merge pull request ruby-i18n#628 from sambostock/bulk-translation-mis…
Browse files Browse the repository at this point in the history
…sing

Consistently return array from bulk lookup, even if translation(s) missing
  • Loading branch information
radar authored Jul 10, 2022
2 parents b805537 + 8a698d7 commit 4c7343f
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 10 deletions.
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

0 comments on commit 4c7343f

Please sign in to comment.