Class: RuboCop::Cop::Rails::ActiveRecordOverride

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/active_record_override.rb

Overview

Checks for overriding built-in Active Record methods instead of using callbacks.

Examples:

# bad
class Book < ApplicationRecord
  def save
    self.title = title.upcase!
    super
  end
end

# good
class Book < ApplicationRecord
  before_save :upcase_title

  def upcase_title
    self.title = title.upcase!
  end
end

Constant Summary collapse

MSG =
'Use %<prefer>s callbacks instead of overriding the Active Record method `%<bad>s`.'
BAD_METHODS =
%i[create destroy save update].freeze
ACTIVE_RECORD_CLASSES =
%w[ApplicationRecord ActiveModel::Base ActiveRecord::Base].freeze

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/rubocop/cop/rails/active_record_override.rb', line 32

def on_def(node)
  return unless BAD_METHODS.include?(node.method_name)

  parent_class_name = find_parent_class_name(node)
  return unless active_model?(parent_class_name)

  return unless node.descendants.any?(&:zsuper_type?)

  add_offense(node, message: message(node.method_name))
end