diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ca6eaf054..1288d2112f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ * [#140](https://github.com/rubocop-hq/rubocop-performance/pull/140): Add new `Performance/CollectionLiteralInLoop` cop. ([@fatkodima][]) * [#137](https://github.com/rubocop-hq/rubocop-performance/pull/137): Add new `Performance/Sum` cop. ([@fatkodima][]) +### Bug fixes + +* [#159](https://github.com/rubocop-hq/rubocop-performance/pull/159): Fix a false positive for `Performance/AncestorsInclude` when receiver is a variable. ([@koic][]) + ### Changes * [#154](https://github.com/rubocop-hq/rubocop-performance/pull/154): Require RuboCop 0.87 or higher. ([@koic][]) diff --git a/lib/rubocop/cop/performance/ancestors_include.rb b/lib/rubocop/cop/performance/ancestors_include.rb index 763f44038a..62ae0cd19c 100644 --- a/lib/rubocop/cop/performance/ancestors_include.rb +++ b/lib/rubocop/cop/performance/ancestors_include.rb @@ -25,17 +25,23 @@ class AncestorsInclude < Base def on_send(node) return unless (subclass, superclass = ancestors_include_candidate?(node)) + return if subclass && !subclass.const_type? - location_of_ancestors = node.children[0].loc.selector.begin_pos - end_location = node.loc.selector.end_pos - range = range_between(location_of_ancestors, end_location) - - add_offense(range) do |corrector| + add_offense(range(node)) do |corrector| subclass_source = subclass ? subclass.source : 'self' corrector.replace(node, "#{subclass_source} <= #{superclass.source}") end end + + private + + def range(node) + location_of_ancestors = node.children[0].loc.selector.begin_pos + end_location = node.loc.selector.end_pos + + range_between(location_of_ancestors, end_location) + end end end end diff --git a/spec/rubocop/cop/performance/ancestors_include_spec.rb b/spec/rubocop/cop/performance/ancestors_include_spec.rb index cd81456018..7810c4bc04 100644 --- a/spec/rubocop/cop/performance/ancestors_include_spec.rb +++ b/spec/rubocop/cop/performance/ancestors_include_spec.rb @@ -25,6 +25,12 @@ RUBY end + it 'does not register an offense when receiver is not a consntant' do + expect_no_offenses(<<~RUBY) + expect(object_one.ancestors.include?(object_two)).to eq(true) + RUBY + end + it 'does not register an offense when using `<=`' do expect_no_offenses(<<~RUBY) Class <= Kernel