class RuboCop::Cop::Rails::AfterCommitOverride

This cop 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.

@example

# 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

Constants

AFTER_COMMIT_CALLBACKS
MSG

Public Instance Methods

on_class(class_node) click to toggle source
# File lib/rubocop/cop/rails/after_commit_override.rb, line 45
def on_class(class_node)
  seen_callback_names = {}

  each_after_commit_callback(class_node) do |node|
    callback_name = node.arguments[0].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

Private Instance Methods

after_commit_callback?(node) click to toggle source
# File lib/rubocop/cop/rails/after_commit_override.rb, line 78
def after_commit_callback?(node)
  AFTER_COMMIT_CALLBACKS.include?(node.method_name)
end
class_send_nodes(class_node) click to toggle source
# File lib/rubocop/cop/rails/after_commit_override.rb, line 66
def class_send_nodes(class_node)
  class_def = class_node.body

  return [] unless class_def

  if class_def.send_type?
    [class_def]
  else
    class_def.each_child_node(:send).to_a
  end
end
each_after_commit_callback(class_node) { |node| ... } click to toggle source
# File lib/rubocop/cop/rails/after_commit_override.rb, line 60
def each_after_commit_callback(class_node)
  class_send_nodes(class_node).each do |node|
    yield node if after_commit_callback?(node) && named_callback?(node)
  end
end
named_callback?(node) click to toggle source
# File lib/rubocop/cop/rails/after_commit_override.rb, line 82
def named_callback?(node)
  name = node.first_argument
  return false unless name

  name.sym_type?
end