From 81df724a0f8ce91683037c44f064091f8a3d1b10 Mon Sep 17 00:00:00 2001 From: Masataka Pocke Kuwabara Date: Mon, 7 Sep 2020 15:11:20 +0900 Subject: [PATCH] [Fix #345] Fix error of `Rails/AfterCommitOverride` on `after_commit` with a lambda --- CHANGELOG.md | 4 ++++ lib/rubocop/cop/rails/after_commit_override.rb | 9 ++++++++- .../cop/rails/after_commit_override_spec.rb | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e52c5088d9..3ee83edaaf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#345](https://github.com/rubocop-hq/rubocop-rails/issues/345): Fix error of `Rails/AfterCommitOverride` on `after_commit` with a lambda. ([@pocke][]) + ## 2.8.0 (2020-09-04) ### New features diff --git a/lib/rubocop/cop/rails/after_commit_override.rb b/lib/rubocop/cop/rails/after_commit_override.rb index 8d3c6230e6..f144f42f47 100644 --- a/lib/rubocop/cop/rails/after_commit_override.rb +++ b/lib/rubocop/cop/rails/after_commit_override.rb @@ -59,7 +59,7 @@ def on_class(class_node) def each_after_commit_callback(class_node) class_send_nodes(class_node).each do |node| - yield node if after_commit_callback?(node) + yield node if after_commit_callback?(node) && named_callback?(node) end end @@ -78,6 +78,13 @@ def class_send_nodes(class_node) def after_commit_callback?(node) AFTER_COMMIT_CALLBACKS.include?(node.method_name) end + + def named_callback?(node) + name = node.first_argument + return false unless name + + name.sym_type? + end end end end diff --git a/spec/rubocop/cop/rails/after_commit_override_spec.rb b/spec/rubocop/cop/rails/after_commit_override_spec.rb index c8bcd6b5d5..5d4c47afd5 100644 --- a/spec/rubocop/cop/rails/after_commit_override_spec.rb +++ b/spec/rubocop/cop/rails/after_commit_override_spec.rb @@ -32,4 +32,22 @@ class User < ApplicationRecord end RUBY end + + it 'does not register an offense when the callbacks are defined with lambdas' do + expect_no_offenses(<<~RUBY) + class User < ApplicationRecord + after_commit -> { foo } + after_destroy_commit -> { foo } + end + RUBY + end + + it 'ignores after_commit method call without arguments' do + expect_no_offenses(<<~RUBY) + class User < ApplicationRecord + after_commit + after_destroy_commit + end + RUBY + end end