Class: RuboCop::Cop::Rails::AfterCommitOverride

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

Overview

Enforces that there is only one call to ‘after_commit` (and its aliases - `after_create_commit`, `after_update_commit`, and `after_destroy_commit`) with the same callback name per model.

Examples:

# bad
# This won't be triggered.
after_create_commit :log_action

# This will override the callback added by
# after_create_commit.
after_update_commit :log_action

# bad
# This won't be triggered.
after_commit :log_action, on: :create
# This won't be triggered.
after_update_commit :log_action
# This will override both previous callbacks.
after_commit :log_action, on: :destroy

# good
after_save_commit :log_action

# good
after_create_commit :log_create_action
after_update_commit :log_update_action

Constant Summary collapse

MSG =
'There can only be one `after_*_commit :%<name>s` hook defined for a model.'
AFTER_COMMIT_CALLBACKS =
%i[
  after_commit
  after_create_commit
  after_update_commit
  after_save_commit
  after_destroy_commit
].freeze

Instance Method Summary collapse

Methods included from ClassSendNodeHelper

#class_send_nodes

Instance Method Details

#on_class(class_node) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rubocop/cop/rails/after_commit_override.rb', line 47

def on_class(class_node)
  seen_callback_names = {}

  each_after_commit_callback(class_node) do |node|
    callback_name = node.first_argument.value
    if seen_callback_names.key?(callback_name)
      add_offense(node, message: format(MSG, name: callback_name))
    else
      seen_callback_names[callback_name] = true
    end
  end
end