module ViewComponent::Translatable

Constants

HTML_SAFE_TRANSLATION_KEY

Public Instance Methods

_after_compile() click to toggle source
Calls superclass method
# File lib/view_component/translatable.rb, line 23
def _after_compile
  super

  return if CompileCache.compiled? self

  if (translation_files = _sidecar_files(%w[yml yaml])).any?
    self.i18n_backend = I18nBackend.new(
      i18n_scope: i18n_scope,
      load_paths: translation_files,
    )
  else
    # Cleanup if translations file has been removed since the last compilation
    self.i18n_backend = nil
  end
end
i18n_scope() click to toggle source
# File lib/view_component/translatable.rb, line 19
def i18n_scope
  @i18n_scope ||= virtual_path.sub(%r{^/}, "").gsub(%r{/_?}, ".")
end
t(key = nil, **options)
Alias for: translate
translate(key = nil, **options) click to toggle source
Calls superclass method
# File lib/view_component/translatable.rb, line 65
def translate(key = nil, **options)
  return super unless i18n_backend
  return key.map { |k| translate(k, **options) } if key.is_a?(Array)

  locale = options.delete(:locale) || ::I18n.locale
  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)
    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

  translated
end
Also aliased as: t