Class: RuboCop::Cop::DevDoc::I18n::RequireTranslation

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/dev_doc/i18n/require_translation.rb

Overview

Flag hardcoded user-facing strings in glib JSON-UI component props.

## Rationale Glib components render text from props like ‘text:`, `label:`, and `title:`. Passing a string literal ships untranslatable copy — it can never be localized and bypasses the I18n catalog. Pass `t(’…‘)` (or any non-literal) so the text resolves through the locale files.

Only the hash form is checked (‘view.p text: ’…‘`). Empty/whitespace strings are ignored — they carry no user-facing text. An interpolated string (`“Hi #name”`) is flagged because its literal portions are still hardcoded copy — unless it interpolates a `t(…)` (or `translate`/`I18n.t`) call, which is treated as positive localization and left alone.

The watched method names and localizable keys are configurable via ‘WatchedMethods:` and `LocalizableKeys:`.

❌ Hardcoded — can't be translated
view.p text: 'Welcome'
view.fields_text label: 'Email'

✔️ Resolved through I18n
view.p text: t('home.welcome')
view.fields_text label: t('user.email')
view.p text: "#{t('home.welcome')}, #{user.name}"

Examples:

# bad
view.p text: 'Welcome'

# bad
view.fields_text label: 'Email'

# bad (interpolation, but no translation call)
view.p text: "Hi #{name}"

# good
view.p text: t('home.welcome')

# good (interpolates a translation call)
view.p text: "#{t('home.greeting')} #{user.name}"

# good (non-literal — not flagged)
view.p text: user.name

Constant Summary collapse

MSG =
'Localize this string: pass `t(...)` instead of a hardcoded ' \
'string for `%<key>s:`.'.freeze
DEFAULT_WATCHED_METHODS =
%w[
  h1 h2 h3 h4 h5 p label markdown
  fields_text fields_number fields_select fields_password
  fields_textarea fields_check fields_checkGroup fields_chipGroup
  fields_timeZone fields_radioGroup fields_date fields_datetime
].freeze
DEFAULT_LOCALIZABLE_KEYS =
%w[
  title subtitle subsubtitle label placeholder text
].freeze
TRANSLATION_METHODS =
%i[t translate].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object Also known as: on_csend



67
68
69
70
71
72
73
74
75
# File 'lib/rubocop/cop/dev_doc/i18n/require_translation.rb', line 67

def on_send(node)
  return unless watched_methods.include?(node.method_name.to_s)

  node.arguments.each do |arg|
    next unless arg.hash_type?

    arg.pairs.each { |pair| check_pair(pair) }
  end
end