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/
TRANSLATION_EXTENSIONS =
%w[yml yaml].freeze

Instance Method Summary collapse

Instance Method Details

#i18n_scopeObject

Exposes .i18n_scope as an instance method



123
124
125
# File 'lib/view_component/translatable.rb', line 123

def i18n_scope
  self.class.i18n_scope
end

#translate(key = nil, **options) ⇒ Object Also known as: t



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/view_component/translatable.rb', line 91

def translate(key = nil, **options)
  raise ViewComponent::TranslateCalledBeforeRenderError if view_context.nil?

  return super unless i18n_backend
  return key.map { |k| translate(k, **options) } if key.is_a?(Array)

  locale = options.delete(:locale) || ::I18n.locale
  key = self.class.i18n_key(key, options.delete(:scope))
  as_html = HTML_SAFE_TRANSLATION_KEY.match?(key)

  html_escape_translation_options!(options) if as_html

  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

    translated = html_safe_translation(translated) if as_html
    translated
  else
    super(key, locale: locale, **options)
  end
end