Skip to content

Commit

Permalink
Merge pull request #9970 from mtsmfm/sort-with-arg
Browse files Browse the repository at this point in the history
Don't register an offense when sort method has arguments
  • Loading branch information
koic committed Aug 5, 2021
2 parents 52805b6 + 9dcc142 commit 4460b6d
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
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

0 comments on commit 4460b6d

Please sign in to comment.