Class: Keela::Strategies::I18nKeys

Inherits:
Keela::Strategy show all
Defined in:
lib/keela/strategies/i18n_keys.rb

Overview

Detects unused I18n translation keys in locale files.

Definitions are extracted from YAML locale files (config/locales/*.yml) and flattened to dot notation (e.g., "users.show.title").

Usage is detected by searching for:

- I18n.t("key") or I18n.t('key')
- t("key") or t('key')
- t(:key)
- .human_attribute_name(:attr)

Note: Lazy lookup (t('.title') in views) is not yet supported.

Instance Method Summary collapse

Instance Method Details

#definition_file_patternObject



25
26
27
28
# File 'lib/keela/strategies/i18n_keys.rb', line 25

def definition_file_pattern
  # Match locale YAML files
  %r{config/locales/.*\.ya?ml$}
end

#extract_definition(_line) ⇒ Object



45
46
47
48
# File 'lib/keela/strategies/i18n_keys.rb', line 45

def extract_definition(_line)
  # Not used - we override extract_definitions_from_file instead
  nil
end

#extract_definitions_from_file(filepath, _lines) ⇒ Object

Override: I18n keys need special YAML parsing, not line-by-line



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/keela/strategies/i18n_keys.rb', line 31

def extract_definitions_from_file(filepath, _lines)
  return [] unless File.exist?(filepath)

  content = YAML.load_file(filepath, permitted_classes: [Symbol]) || {}
  flatten_keys(content).map do |key|
    # Remove the locale prefix (e.g., "en.users.show" -> "users.show")
    key_without_locale = key.sub(/^[a-z]{2}(-[A-Z]{2})?\./, "")
    { name: key_without_locale, file: filepath }
  end
rescue Psych::SyntaxError => e
  warn "Warning: Could not parse #{filepath}: #{e.message}"
  []
end

#nameObject



21
22
23
# File 'lib/keela/strategies/i18n_keys.rb', line 21

def name
  "i18n_keys"
end

#skip_comments?Boolean

Returns:

  • (Boolean)


66
67
68
# File 'lib/keela/strategies/i18n_keys.rb', line 66

def skip_comments?
  true
end

#usage_regex(name) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/keela/strategies/i18n_keys.rb', line 50

def usage_regex(name)
  # Match various I18n lookup patterns:
  #   I18n.t("users.show.title")
  #   I18n.t('users.show.title')
  #   t("users.show.title")
  #   t('users.show.title')
  #   t(:users_show_title) - symbol form (underscored)
  #
  # Also match partial keys for lazy lookup support:
  #   t(".title") in a view could match "users.show.title"
  quoted_name = Regexp.quote(name)

  # Build pattern that matches the key in quotes or as a symbol
  /(?:I18n\.)?t\s*\(\s*["':]+#{quoted_name}["']?\s*[,)]/
end