Module: ViewComponent::Translatable
- Extended by:
- ActiveSupport::Concern
- Included in:
- Base
- Defined in:
- lib/view_component/translatable.rb
Defined Under Namespace
Classes: I18nBackend
Constant Summary collapse
- HTML_SAFE_TRANSLATION_KEY =
/(?:_|\b)html\z/
Instance Method Summary collapse
- #html_safe_translation(translation) ⇒ Object
-
#i18n_scope ⇒ Object
Exposes .i18n_scope as an instance method.
- #translate(key = nil, **options) ⇒ Object (also: #t)
Instance Method Details
#html_safe_translation(translation) ⇒ Object
104 105 106 107 108 109 110 111 112 113 |
# File 'lib/view_component/translatable.rb', line 104 def html_safe_translation(translation) if translation.respond_to?(:map) translation.map { |element| html_safe_translation(element) } else # It's assumed here that objects loaded by the i18n backend will respond to `#html_safe?`. # It's reasonable that if we're in Rails, `active_support/core_ext/string/output_safety.rb` # will provide this to `Object`. translation.html_safe end end |
#i18n_scope ⇒ Object
Exposes .i18n_scope as an instance method
100 101 102 |
# File 'lib/view_component/translatable.rb', line 100 def i18n_scope self.class.i18n_scope end |
#translate(key = nil, **options) ⇒ Object Also known as: t
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/view_component/translatable.rb', line 62 def translate(key = nil, **) return super unless i18n_backend return key.map { |k| translate(k, **) } if key.is_a?(Array) locale = .delete(:locale) || ::I18n.locale scope = .delete(:scope) scope = scope.join(".") if scope.is_a? Array key = key&.to_s unless key.is_a?(String) key = "#{scope}.#{key}" if scope key = "#{i18n_scope}#{key}" if key.start_with?(".") if HTML_SAFE_TRANSLATION_KEY.match?(key) () end if key.start_with?(i18n_scope + ".") translated = catch(:exception) do i18n_backend.translate(locale, key, ) end # Fallback to the global translations if translated.is_a? ::I18n::MissingTranslation return super(key, locale: locale, **) end if HTML_SAFE_TRANSLATION_KEY.match?(key) translated = html_safe_translation(translated) end translated else super(key, locale: locale, **) end end |