Module: ViewComponent::Translatable

Extended by:
ActiveSupport::Concern
Defined in:
lib/view_component/translatable.rb

Defined Under Namespace

Classes: I18nBackend

Constant Summary collapse

HTML_SAFE_TRANSLATION_KEY =
/(?:_|\b)html\z/.freeze

Instance Method Summary collapse

Instance Method Details

#i18n_scopeObject

Exposes .i18n_scope as an instance method



96
97
98
# File 'lib/view_component/translatable.rb', line 96

def i18n_scope
  self.class.i18n_scope
end

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



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
# 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?(".")

  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

    if HTML_SAFE_TRANSLATION_KEY.match?(key)
      translated = translated.html_safe # rubocop:disable Rails/OutputSafety
    end

    translated
  else
    super(key, locale: locale, **options)
  end
end