From bcf9efef7dc4c392a7ef2fda97fd9a9403f83475 Mon Sep 17 00:00:00 2001 From: Koichi ITO Date: Wed, 5 Aug 2020 20:34:36 +0900 Subject: [PATCH] [Fix #319] Fix an false positive for `Rails/Inquiry` Fixes #319. This PR fixes an false positive for `Rails/Inquiry` when `#inquiry`'s receiver is a variable. It should only detect when receiver is an array literal and a string literal. --- CHANGELOG.md | 1 + lib/rubocop/cop/rails/inquiry.rb | 6 +++++- spec/rubocop/cop/rails/inquiry_spec.rb | 17 +++++++++++++++-- 3 files changed, 21 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 006980c455..53ec2a9f7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ * [#315](https://github.com/rubocop-hq/rubocop-rails/pull/315): Allow to use frozen scope for `Rails/UniqueValidationWithoutIndex`. ([@krim][]) * [#313](https://github.com/rubocop-hq/rubocop-rails/pull/313): Fix `Rails/ActiveRecordCallbacksOrder` to preserve the original callback execution order. ([@eugeneius][]) +* [#319](https://github.com/rubocop-hq/rubocop-rails/issues/319): Fix an false positive for `Rails/Inquiry` when `#inquiry`'s receiver is a variable. ([@koic][]) ### Changes diff --git a/lib/rubocop/cop/rails/inquiry.rb b/lib/rubocop/cop/rails/inquiry.rb index 9acefe3f59..f5ea160187 100644 --- a/lib/rubocop/cop/rails/inquiry.rb +++ b/lib/rubocop/cop/rails/inquiry.rb @@ -26,7 +26,11 @@ class Inquiry < Cop MSG = "Prefer Ruby's comparison operators over Active Support's `inquiry`." def on_send(node) - add_offense(node, location: :selector) if node.method?(:inquiry) && node.arguments.empty? + return unless node.method?(:inquiry) && node.arguments.empty? + return unless (receiver = node.receiver) + return if !receiver.str_type? && !receiver.array_type? + + add_offense(node, location: :selector) end end end diff --git a/spec/rubocop/cop/rails/inquiry_spec.rb b/spec/rubocop/cop/rails/inquiry_spec.rb index 54def5ad9e..d6cfa6de3f 100644 --- a/spec/rubocop/cop/rails/inquiry_spec.rb +++ b/spec/rubocop/cop/rails/inquiry_spec.rb @@ -3,16 +3,29 @@ RSpec.describe RuboCop::Cop::Rails::Inquiry do subject(:cop) { described_class.new } - it 'registers an offense when using `#inquiry`' do + it 'registers an offense when using `String#inquiry`' do expect_offense(<<~RUBY) 'two'.inquiry ^^^^^^^ Prefer Ruby's comparison operators over Active Support's `inquiry`. RUBY end + it 'registers an offense when using `Array#inquiry`' do + expect_offense(<<~RUBY) + [foo, bar].inquiry + ^^^^^^^ Prefer Ruby's comparison operators over Active Support's `inquiry`. + RUBY + end + + it "does not register an offense when `#inquiry`'s receiver is a variable" do + expect_no_offenses(<<~RUBY) + foo.inquiry + RUBY + end + it 'does not register an offense when using `#inquiry` with arguments' do expect_no_offenses(<<~RUBY) - foo.inquiry(bar) + 'foo'.inquiry(bar) RUBY end end