diff --git a/CHANGELOG.md b/CHANGELOG.md index 41db0807bd..a5cd7fab38 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,10 @@ ## master (unreleased) +### Bug fixes + +* [#147](https://github.com/rubocop-hq/rubocop-performance/issues/147): Fix an error for `Performance/AncestorsInclude` when using `ancestors.include? without receiver. ([@koic][]) + ## 1.7.0 (2020-07-07) ### New features diff --git a/lib/rubocop/cop/performance/ancestors_include.rb b/lib/rubocop/cop/performance/ancestors_include.rb index ab02fac7c7..53bf6a6b85 100644 --- a/lib/rubocop/cop/performance/ancestors_include.rb +++ b/lib/rubocop/cop/performance/ancestors_include.rb @@ -35,7 +35,9 @@ def on_send(node) def autocorrect(node) ancestors_include_candidate?(node) do |subclass, superclass| lambda do |corrector| - corrector.replace(node, "#{subclass.source} <= #{superclass.source}") + subclass_source = subclass ? subclass.source : 'self.class' + + corrector.replace(node, "#{subclass_source} <= #{superclass.source}") end end end diff --git a/spec/rubocop/cop/performance/ancestors_include_spec.rb b/spec/rubocop/cop/performance/ancestors_include_spec.rb index d870eff2d7..45c0a56b11 100644 --- a/spec/rubocop/cop/performance/ancestors_include_spec.rb +++ b/spec/rubocop/cop/performance/ancestors_include_spec.rb @@ -14,6 +14,17 @@ RUBY end + it 'registers an offense and corrects when using `ancestors.include? without receiver`' do + expect_offense(<<~RUBY) + ancestors.include?(Klass) + ^^^^^^^^^^^^^^^^^^ Use `<=` instead of `ancestors.include?`. + RUBY + + expect_correction(<<~RUBY) + self.class <= Klass + RUBY + end + it 'does not register an offense when using `<=`' do expect_no_offenses(<<~RUBY) Class <= Kernel