Class: RuboCop::Cop::Rails::DotSeparatedKeys

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
RangeHelp
Defined in:
lib/rubocop/cop/rails/dot_separated_keys.rb

Overview

Enforces the use of dot-separated locale keys instead of specifying the ‘:scope` option with an array or a single symbol in `I18n` translation methods. Dot-separated notation is easier to read and trace the hierarchy.

Examples:

# bad
I18n.t :record_invalid, scope: [:activerecord, :errors, :messages]
I18n.t :title, scope: :invitation

# good
I18n.t 'activerecord.errors.messages.record_invalid'
I18n.t :record_invalid, scope: 'activerecord.errors.messages'

Constant Summary collapse

MSG =
'Use the dot-separated keys instead of specifying the `:scope` option.'
TRANSLATE_METHODS =
%i[translate t].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rubocop/cop/rails/dot_separated_keys.rb', line 32

def on_send(node)
  return unless TRANSLATE_METHODS.include?(node.method_name)

  translate_with_scope?(node) do |key_node, scope_node|
    return unless should_convert_scope?(scope_node)

    add_offense(scope_node) do |corrector|
      # Eat the comma on the left.
      range = range_with_surrounding_space(scope_node.source_range, side: :left)
      range = range_with_surrounding_comma(range, :left)
      corrector.remove(range)

      corrector.replace(key_node, new_key(key_node, scope_node))
    end
  end
end