Pass default values for `translate` through I18n
A default value can be a string that needs interpolation, Hash that needs resolution via the `:count` option, or a Proc that needs evaluation. Therefore, pass default values through `I18n.translate` to handle these cases. Fixes #26032. Fixes #41277. Fixes #41380.
This commit is contained in:
parent
567cc80fc6
commit
dd884eb425
|
@ -1,3 +1,8 @@
|
|||
* The `translate` helper now passes `default` values that aren't
|
||||
translation keys through `I18n.translate` for interpolation.
|
||||
|
||||
*Jonathan Hefner*
|
||||
|
||||
* Adds option `extname` to `stylesheet_link_tag` to skip default
|
||||
`.css` extension appended to the stylesheet path.
|
||||
|
||||
|
|
|
@ -93,7 +93,9 @@ module ActionView
|
|||
break translated unless translated.equal?(MISSING_TRANSLATION)
|
||||
end
|
||||
|
||||
break alternatives.first if alternatives.present? && !alternatives.first.is_a?(Symbol)
|
||||
if alternatives.present? && !alternatives.first.is_a?(Symbol)
|
||||
break alternatives.first && I18n.translate(**options, default: alternatives)
|
||||
end
|
||||
|
||||
first_key ||= key
|
||||
key = alternatives&.shift
|
||||
|
|
|
@ -158,11 +158,6 @@ class TranslationHelperTest < ActiveSupport::TestCase
|
|||
I18n.exception_handler = old_exception_handler
|
||||
end
|
||||
|
||||
def test_hash_default
|
||||
default = { separator: ".", delimiter: "," }
|
||||
assert_equal default, translate(:'special.number.format', default: default)
|
||||
end
|
||||
|
||||
def test_translation_returning_an_array
|
||||
expected = %w(foo bar)
|
||||
assert_equal expected, translate(:"translations.array")
|
||||
|
@ -328,6 +323,27 @@ class TranslationHelperTest < ActiveSupport::TestCase
|
|||
assert_equal "A Generic String", translation
|
||||
end
|
||||
|
||||
def test_translate_with_interpolated_string_default
|
||||
translation = translate(:"translations.missing", default: "An %{kind} String", kind: "Interpolated")
|
||||
assert_equal "An Interpolated String", translation
|
||||
end
|
||||
|
||||
def test_translate_with_hash_default
|
||||
hash = { one: "%{count} thing", other: "%{count} things" }
|
||||
assert_equal hash, translate(:"translations.missing", default: hash)
|
||||
end
|
||||
|
||||
def test_translate_with_hash_default_and_count
|
||||
hash = { one: "%{count} thing", other: "%{count} things" }
|
||||
assert_equal "1 thing", translate(:"translations.missing", default: hash, count: 1)
|
||||
assert_equal "2 things", translate(:"translations.missing", default: hash, count: 2)
|
||||
end
|
||||
|
||||
def test_translate_with_proc_default
|
||||
translation = translate(:"translations.missing", default: Proc.new { "From Proc" })
|
||||
assert_equal "From Proc", translation
|
||||
end
|
||||
|
||||
def test_translate_with_object_default
|
||||
translation = translate(:'translations.missing', default: 123)
|
||||
assert_equal 123, translation
|
||||
|
|
Loading…
Reference in New Issue