From 7b31f4482d04ad95abf8223f29a64aec6ffc2172 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Sun, 6 Sep 2020 04:00:16 +0900 Subject: [PATCH] Fix a false positive for `Rails/DynamicFindBy` This PR fixes a false positive for `Rails/DynamicFindBy` when any of the arguments are splat argument. ```console % cat example.rb find_by_scan(*args) % bundle exec rubocop -a example.rb (snip) Inspecting 1 file E Offenses: example.rb:1:1: C: [Corrected] Rails/DynamicFindBy: Use find_by instead of dynamic find_by_scan. find_by_scan(*args) ^^^^^^^^^^^^^^^^^^^ example.rb:1:15: E: Lint/Syntax: unexpected token tSTAR (Using Ruby 2.7 parser; configure using TargetRubyVersion parameter, under AllCops) find_by(scan: *args) ^ 1 file inspected, 2 offenses detected, 1 offense corrected % cat example.rb find_by(scan: *args) % ruby -c example.rb example.rb:1: syntax error, unexpected * find_by(scan: *args) ``` --- CHANGELOG.md | 1 + lib/rubocop/cop/rails/dynamic_find_by.rb | 1 + spec/rubocop/cop/rails/dynamic_find_by_spec.rb | 8 ++++++++ 3 files changed, 10 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3ee83edaaf..9a81564a33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Bug fixes * [#345](https://github.com/rubocop-hq/rubocop-rails/issues/345): Fix error of `Rails/AfterCommitOverride` on `after_commit` with a lambda. ([@pocke][]) +* [#346](https://github.com/rubocop-hq/rubocop-rails/pull/346): Fix a false positive for `Rails/DynamicFindBy` when any of the arguments are splat argument. ([@koic][]) ## 2.8.0 (2020-09-04) diff --git a/lib/rubocop/cop/rails/dynamic_find_by.rb b/lib/rubocop/cop/rails/dynamic_find_by.rb index 3c2e349b59..e86efd6d26 100644 --- a/lib/rubocop/cop/rails/dynamic_find_by.rb +++ b/lib/rubocop/cop/rails/dynamic_find_by.rb @@ -41,6 +41,7 @@ def on_send(node) method_name = node.method_name static_name = static_method_name(method_name) return unless static_name + return if node.arguments.any?(&:splat_type?) add_offense(node, message: format(MSG, static_name: static_name, diff --git a/spec/rubocop/cop/rails/dynamic_find_by_spec.rb b/spec/rubocop/cop/rails/dynamic_find_by_spec.rb index 7866a49dad..d5655dc582 100644 --- a/spec/rubocop/cop/rails/dynamic_find_by_spec.rb +++ b/spec/rubocop/cop/rails/dynamic_find_by_spec.rb @@ -133,6 +133,14 @@ expect_no_offenses('User.find_by(name: name)') end + it 'accepts splat argument' do + expect_no_offenses('User.find_by_scan(*args)') + end + + it 'accepts any of the arguments are splat argument' do + expect_no_offenses('User.find_by_foo_and_bar(arg, *args)') + end + it 'accepts method in whitelist' do expect_no_offenses(<<~RUBY) User.find_by_sql(["select * from users where name = ?", name])