diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 85a673190..f24beb436 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,6 +7,10 @@ title: Changelog ## main +* Fix support for the `default:` option for a global translation. + + *Elia Schito* + * Ensure i18n scope is a symbol to protect lookups. *Simon Fish* diff --git a/lib/view_component/translatable.rb b/lib/view_component/translatable.rb index 617dda144..b69227408 100644 --- a/lib/view_component/translatable.rb +++ b/lib/view_component/translatable.rb @@ -70,21 +70,25 @@ def translate(key = nil, **options) key = key&.to_s unless key.is_a?(String) key = "#{i18n_scope}#{key}" if key.start_with?(".") - translated = - catch(:exception) do - i18n_backend.translate(locale, key, options) + if key.start_with?(i18n_scope + ".") + translated = + catch(:exception) do + i18n_backend.translate(locale, key, options) + end + + # Fallback to the global translations + if translated.is_a? ::I18n::MissingTranslation + return super(key, locale: locale, **options) end - # Fallback to the global translations - if translated.is_a? ::I18n::MissingTranslation - return super(key, locale: locale, **options) - end + if HTML_SAFE_TRANSLATION_KEY.match?(key) + translated = translated.html_safe # rubocop:disable Rails/OutputSafety + end - if HTML_SAFE_TRANSLATION_KEY.match?(key) - translated = translated.html_safe # rubocop:disable Rails/OutputSafety + translated + else + super(key, locale: locale, **options) end - - translated end alias :t :translate diff --git a/test/view_component/translatable_test.rb b/test/view_component/translatable_test.rb index 59d63c933..1e942266c 100644 --- a/test/view_component/translatable_test.rb +++ b/test/view_component/translatable_test.rb @@ -43,9 +43,9 @@ def test_symbol_keys end def test_converts_key_to_string_as_necessary - key = Struct.new(:to_s).new(".hello") + klass = Struct.new(:to_s) + key = klass.new(".hello") assert_equal "Hello from sidecar translations!", translate(key) - assert_equal key, translate(:"translations.missing", default: key) end def test_translate_marks_translations_named_html_as_safe_html @@ -75,6 +75,15 @@ def test_translate_uses_the_helper_when_no_sidecar_file_is_provided ViewComponent::CompileCache.cache.delete(TranslatableComponent) end + def test_default + default_value = Object.new + + assert_equal default_value, translate(".missing", default: default_value) + assert_equal default_value, translate("missing", default: default_value) + assert_equal "Hello from Rails translations!", translate("hello", default: default_value) + assert_equal "Hello from sidecar translations!", translate(".hello", default: default_value) + end + private def translate(key, **options)