Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Don't register an offense when sort method has arguments #9970

Merged
merged 1 commit into from Aug 5, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_redundant_sort_false_positive.md
@@ -0,0 +1 @@
* [#9970](https://github.com/rubocop/rubocop/pull/9970): Don't register an offense when sort method has arguments for `Style/RedundantSort` cop. ([@mtsmfm][])
4 changes: 2 additions & 2 deletions lib/rubocop/cop/style/redundant_sort.rb
Expand Up @@ -60,8 +60,8 @@ class RedundantSort < Base
# @!method redundant_sort?(node)
def_node_matcher :redundant_sort?, <<~MATCHER
{
(send $(send _ $:sort ...) ${:last :first})
(send $(send _ $:sort ...) ${:[] :at :slice} {(int 0) (int -1)})
(send $(send _ $:sort) ${:last :first})
(send $(send _ $:sort) ${:[] :at :slice} {(int 0) (int -1)})

(send $(send _ $:sort_by _) ${:last :first})
(send $(send _ $:sort_by _) ${:[] :at :slice} {(int 0) (int -1)})
Expand Down
9 changes: 9 additions & 0 deletions spec/rubocop/cop/style/redundant_sort_spec.rb
Expand Up @@ -206,6 +206,11 @@
expect_no_offenses('[1, 2, 3].sort.first(1)')
end

# Some gems like mongo provides sort method with an argument
it 'does not register an offense when sort has an argument' do
expect_no_offenses('mongo_client["users"].find.sort(_id: 1).first')
end

it 'does not register an offense for sort!.first' do
expect_no_offenses('[1, 2, 3].sort!.first')
end
Expand Down Expand Up @@ -240,6 +245,10 @@
it 'does not register an offense when at(-2) is called on sort_by' do
expect_no_offenses('[1, 2, 3].sort_by(&:foo).at(-2)')
end

it 'does not register an offense when [-1] is called on sort with an argument' do
expect_no_offenses('mongo_client["users"].find.sort(_id: 1)[-1]')
end
end

context '>= Ruby 2.7', :ruby27 do
Expand Down