Skip to content

Commit

Permalink
[Fix rubocop#12301] Make Style/RedundantFilterChain aware of safe n…
Browse files Browse the repository at this point in the history
…avigation

Fixes rubocop#12301.

This PR makes `Style/RedundantFilterChain` aware of safe navigation.
  • Loading branch information
koic committed Oct 21, 2023
1 parent a797c98 commit a17909d
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#12301](https://github.com/rubocop/rubocop/issues/12301): Make `Style/RedundantFilterChain` aware of safe navigation operator. ([@koic][])
7 changes: 4 additions & 3 deletions lib/rubocop/cop/style/redundant_filter_chain.rb
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,10 @@ class RedundantFilterChain < Base

# @!method select_predicate?(node)
def_node_matcher :select_predicate?, <<~PATTERN
(send
(call
{
(block $(send _ {:select :filter :find_all}) ...)
$(send _ {:select :filter :find_all} block_pass_type?)
(block $(call _ {:select :filter :find_all}) ...)
$(call _ {:select :filter :find_all} block_pass_type?)
}
${:#{RESTRICT_ON_SEND.join(' :')}})
PATTERN
Expand All @@ -87,6 +87,7 @@ def on_send(node)
register_offense(select_node, node)
end
end
alias on_csend on_send

private

Expand Down
46 changes: 46 additions & 0 deletions spec/rubocop/cop/style/redundant_filter_chain_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,52 @@
arr.#{method}(&:odd?).any? { |x| x > 10 }
RUBY
end

context 'when using safe navigation operator' do
it "registers an offense when using `##{method}` followed by `#any?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.any?
^{method}^^^^^^^^^^^^^^^^^^^^ Use `any?` instead of `#{method}.any?`.
RUBY

expect_correction(<<~RUBY)
arr&.any? { |x| x > 1 }
RUBY
end

it "registers an offense when using `##{method}` followed by `#empty?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.empty?
^{method}^^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.empty?`.
RUBY

expect_correction(<<~RUBY)
arr&.none? { |x| x > 1 }
RUBY
end

it "registers an offense when using `##{method}` followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method} { |x| x > 1 }&.none?
^{method}^^^^^^^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY

expect_correction(<<~RUBY)
arr&.none? { |x| x > 1 }
RUBY
end

it "registers an offense when using `##{method}` with block-pass followed by `#none?`" do
expect_offense(<<~RUBY, method: method)
arr&.%{method}(&:odd?)&.none?
^{method}^^^^^^^^^^^^^^^ Use `none?` instead of `#{method}.none?`.
RUBY

expect_correction(<<~RUBY)
arr&.none?(&:odd?)
RUBY
end
end
end

it 'does not register an offense when using `#any?`' do
Expand Down

0 comments on commit a17909d

Please sign in to comment.