Class: RuboCop::Cop::Locallingo::RelativeI18nKey
- Inherits:
-
Base
- Object
- Base
- RuboCop::Cop::Locallingo::RelativeI18nKey
- Extended by:
- AutoCorrector
- Defined in:
- lib/rubocop/cop/locallingo/relative_i18n_key.rb
Overview
Enforces fully-qualified i18n keys instead of relative keys.
Relative keys (e.g. t(".notice")) depend on Rails' lazy lookup, which is
implicit and fragile: moving a translation between files, renaming an
action, or reusing a string in a different context all silently break the
lookup. Fully qualified keys are explicit and grep-able.
The autocorrector mirrors Rails' lazy-lookup scope, deriving the prefix
from the file path (mapped through ScopedDirectories) plus the enclosing
method name. When the path does not map to a known convention it flags the
offense but leaves qualification to the developer rather than guessing.
The set of scoped directories is configurable so the cop fits apps with different layouts:
Locallingo/RelativeI18nKey:
ScopedDirectories: [controllers, mailers, views, components]
Constant Summary collapse
- MSG =
"Use fully-qualified i18n key instead of relative key `%<key>s`."- DEFAULT_SCOPED_DIRECTORIES =
%w[ controllers mailers views components models services jobs notifiers ].freeze
Instance Method Summary collapse
Instance Method Details
#on_send(node) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/rubocop/cop/locallingo/relative_i18n_key.rb', line 46 def on_send(node) t_with_string_arg?(node) do |key| next unless key.start_with?(".") add_offense(node, message: format(MSG, key:)) do |corrector| qualified = qualify(node, key) next unless qualified corrector.replace(node.first_argument, "\"#{qualified}\"") end end end |
#t_with_string_arg?(node) ⇒ Object
42 43 44 |
# File 'lib/rubocop/cop/locallingo/relative_i18n_key.rb', line 42 def_node_matcher :t_with_string_arg?, <<~PATTERN (send nil? :t (str $_) ...) PATTERN |