Skip to content

Commit

Permalink
[Fix rubocop#11168] Fix an incorrect autocorrect for `Style/ClassEqua…
Browse files Browse the repository at this point in the history
…lityComparison`

Fixes rubocop#11168.

This PR fixes an incorrect autocorrect for `Style/ClassEqualityComparison`
when using instance variable comparison in module.
  • Loading branch information
koic authored and bbatsov committed Nov 10, 2022
1 parent 37d7c02 commit 40dfd9f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#11168](https://github.com/rubocop/rubocop/issues/11168): Fix an incorrect autocorrect for `Style/ClassEqualityComparison` when using instance variable comparison in module. ([@koic][])
12 changes: 7 additions & 5 deletions lib/rubocop/cop/style/class_equality_comparison.rb
Original file line number Diff line number Diff line change
Expand Up @@ -97,12 +97,14 @@ def class_name(class_node, node)
if node.children.first.method?(:name)
return class_node.receiver.source if class_node.receiver

value = class_node.source.delete('"').delete("'")
value.prepend('::') if class_node.each_ancestor(:class, :module).any?
value
else
class_node.source
if class_node.str_type?
value = class_node.source.delete('"').delete("'")
value.prepend('::') if class_node.each_ancestor(:class, :module).any?
return value
end
end

class_node.source
end

def offense_range(receiver_node, node)
Expand Down
21 changes: 21 additions & 0 deletions spec/rubocop/cop/style/class_equality_comparison_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,25 @@ class Bar
RUBY
end
end

context 'with instance variable comparison in module' do
it 'registers and corrects an offense' do
expect_offense(<<~RUBY)
module Foo
def bar?(value)
bar.class.name == @class_name
^^^^^^^^^^^^^^^^^^^^^^^^^ Use `instance_of?(@class_name)` instead of comparing classes.
end
end
RUBY

expect_correction(<<~RUBY)
module Foo
def bar?(value)
bar.instance_of?(@class_name)
end
end
RUBY
end
end
end

0 comments on commit 40dfd9f

Please sign in to comment.