Skip to content

Commit

Permalink
[Fix rubocop#12649] Fix false positives for Style/InverseMethods
Browse files Browse the repository at this point in the history
Fixes rubocop#12649.

This PR fixes false positives for `Style/InverseMethods`
when using relational comparison operator (`<`) with safe navigation operator.
  • Loading branch information
koic committed Jan 24, 2024
1 parent 1f27766 commit b4aa28c
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 2 deletions.
1 change: 1 addition & 0 deletions changelog/fix_false_positives_for_style_inverse_methods.md
@@ -0,0 +1 @@
* [#12649](https://github.com/rubocop/rubocop/issues/12649): Fix false positives for `Style/InverseMethods` when using relational comparison operator (`<`) with safe navigation operator. ([@koic][])
8 changes: 6 additions & 2 deletions lib/rubocop/cop/style/inverse_methods.rb
Expand Up @@ -76,9 +76,9 @@ def self.autocorrect_incompatible_with
PATTERN

def on_send(node)
inverse_candidate?(node) do |_method_call, lhs, method, rhs|
inverse_candidate?(node) do |method_call, lhs, method, rhs|
return unless inverse_methods.key?(method)
return if negated?(node)
return if negated?(node) || relational_comparison_with_safe_navigation?(method_call)
return if part_of_ignored_node?(node)
return if possible_class_hierarchy_check?(lhs, rhs, method)

Expand Down Expand Up @@ -155,6 +155,10 @@ def negated?(node)
node.parent.respond_to?(:method?) && node.parent.method?(:!)
end

def relational_comparison_with_safe_navigation?(node)
node.csend_type? && CLASS_COMPARISON_METHODS.include?(node.method_name)
end

def not_to_receiver(node, method_call)
Parser::Source::Range.new(node.source_range.source_buffer,
node.loc.selector.begin_pos,
Expand Down
24 changes: 24 additions & 0 deletions spec/rubocop/cop/style/inverse_methods_spec.rb
Expand Up @@ -209,6 +209,30 @@ def test_method
end
end

it 'allows comparing for relational comparison operator (`<`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.<(0)
RUBY
end

it 'allows comparing for relational comparison operator (`<=`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.<=(0)
RUBY
end

it 'allows comparing for relational comparison operator (`>`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.>(0)
RUBY
end

it 'allows comparing for relational comparison operator (`>=`) with safe navigation operator' do
expect_no_offenses(<<~RUBY)
!nullable&.>=(0)
RUBY
end

it 'allows comparing camel case constants on the right' do
expect_no_offenses(<<~RUBY)
klass = self.class
Expand Down

0 comments on commit b4aa28c

Please sign in to comment.