Skip to content

Commit

Permalink
Fix a false positive for Style/CaseEquality cop
Browse files Browse the repository at this point in the history
Follow #8322 (comment)

Fix a false positive for `Style/CaseEquality` cop when
the receiver is not a camel cased constant.

The following constant should not be replaced with `is_a?`.
What kind of object is actually assigned depends on the constant. e.g.:

```ruby
REGEXP_CONSTANT === something #=> does not register an offense.
```

This PR will only consider camel-cased constant as class name. e.g.:

```ruby
Array === something #=> auto-correct to `something.is_a?(Array)`
```
  • Loading branch information
koic committed Sep 14, 2020
1 parent 52d5c3a commit 252fe51
Show file tree
Hide file tree
Showing 4 changed files with 10 additions and 1 deletion.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -33,6 +33,7 @@
* [#8698](https://github.com/rubocop-hq/rubocop/pull/8698): Fix cache to avoid encoding exception. ([@marcandre][])
* [#8704](https://github.com/rubocop-hq/rubocop/issues/8704): Fix an error for `Lint/AmbiguousOperator` when using safe navigation operator with a unary operator. ([@koic][])
* [#8661](https://github.com/rubocop-hq/rubocop/pull/8661): Fix an incorrect auto-correct for `Style/MultilineTernaryOperator` when returning a multiline ternary operator expression. ([@koic][])
* [#8526](https://github.com/rubocop-hq/rubocop/pull/8526): Fix a false positive for `Style/CaseEquality` cop when the receiver is not a camel cased constant. ([@koic][])

### Changes

Expand Down
2 changes: 2 additions & 0 deletions lib/rubocop/cop/style/case_equality.rb
Expand Up @@ -39,6 +39,8 @@ class CaseEquality < Base

def on_send(node)
case_equality?(node) do |lhs, rhs|
return if lhs.const_type? && !lhs.module_name?

add_offense(node.loc.selector) do |corrector|
replacement = replacement(lhs, rhs)
corrector.replace(node, replacement) if replacement
Expand Down
2 changes: 1 addition & 1 deletion rubocop.gemspec
Expand Up @@ -38,7 +38,7 @@ Gem::Specification.new do |s|
s.add_runtime_dependency('rainbow', '>= 2.2.2', '< 4.0')
s.add_runtime_dependency('regexp_parser', '>= 1.7')
s.add_runtime_dependency('rexml')
s.add_runtime_dependency('rubocop-ast', '>= 0.3.0', '< 1.0')
s.add_runtime_dependency('rubocop-ast', '>= 0.4.0', '< 1.0')
s.add_runtime_dependency('ruby-progressbar', '~> 1.7')
s.add_runtime_dependency('unicode-display_width', '>= 1.4.0', '< 2.0')

Expand Down
6 changes: 6 additions & 0 deletions spec/rubocop/cop/style/case_equality_spec.rb
Expand Up @@ -8,6 +8,12 @@
RUBY
end

it 'does not register an offense for === when the receiver is not a camel cased constant' do
expect_no_offenses(<<~RUBY)
REGEXP_CONSTANT === var
RUBY
end

it 'registers an offense and corrects for === when the receiver is a regexp' do
expect_offense(<<~RUBY)
/OMG/ === var
Expand Down

0 comments on commit 252fe51

Please sign in to comment.