Class: RuboCop::Cop::Rails::DeprecatedActiveModelErrorsMethods

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

Overview

Checks direct manipulation of ActiveModel#errors as hash. These operations are deprecated in Rails 6.1 and will not work in Rails 7.

Examples:

# bad
user.errors[:name] << 'msg'
user.errors.messages[:name] << 'msg'

# good
user.errors.add(:name, 'msg')

# bad
user.errors[:name].clear
user.errors.messages[:name].clear

# good
user.errors.delete(:name)

# bad
user.errors.keys.include?(:attr)

# good
user.errors.attribute_names.include?(:attr)

Constant Summary collapse

MSG =
'Avoid manipulating ActiveModel errors as hash directly.'
AUTOCORRECTABLE_METHODS =
%i[<< clear keys].freeze
INCOMPATIBLE_METHODS =
%i[keys values to_h to_xml].freeze
MANIPULATIVE_METHODS =
Set[
  *%i[
    << append clear collect! compact! concat
    delete delete_at delete_if drop drop_while fill filter! keep_if
    flatten! insert map! pop prepend push reject! replace reverse!
    rotate! select! shift shuffle! slice! sort! sort_by! uniq! unshift
  ]
].freeze

Instance Method Summary collapse

Instance Method Details

#on_send(node) ⇒ Object



108
109
110
111
112
113
114
115
116
117
118
# File 'lib/rubocop/cop/rails/deprecated_active_model_errors_methods.rb', line 108

def on_send(node)
  any_manipulation?(node) do
    next if target_rails_version <= 6.0 && INCOMPATIBLE_METHODS.include?(node.method_name)

    add_offense(node) do |corrector|
      next if skip_autocorrect?(node)

      autocorrect(corrector, node)
    end
  end
end