Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/fix_rails_order_arguments_cop_false_positives.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1510](https://github.com/rubocop/rubocop-rails/pull/1510): Fix `Rails/OrderArguments` cop false positives when using column index argument. ([@viralpraxis][])
5 changes: 5 additions & 0 deletions lib/rubocop/cop/rails/order_arguments.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ def replacement(order_expressions)
order_arguments.map! { |arg| extract_column_and_direction(arg.strip) }

return if order_arguments.any?(&:nil?)
return if order_arguments.any? { |column_name, _| positional_column?(column_name) }

convert_to_preferred_arguments(order_arguments).join(', ')
end
Expand All @@ -68,6 +69,10 @@ def convert_to_preferred_arguments(order_expressions)
end
end

def positional_column?(column_name)
column_name.match?(/\A\d+\z/)
end

def extract_column_and_direction(order_expression)
return unless (column, direction = ORDER_EXPRESSION_REGEX.match(order_expression)&.captures)

Expand Down
26 changes: 26 additions & 0 deletions spec/rubocop/cop/rails/order_arguments_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,4 +128,30 @@
User.order('LEFT(first_name, 1)')
RUBY
end

context 'with numeric string literal column name' do
it 'does not register an offense for `order` with a string argument' do
expect_no_offenses(<<~RUBY)
User.order('1')
RUBY
end

it 'does not register an offense for `order` with multiple string arguments' do
expect_no_offenses(<<~RUBY)
User.order('1', 'last_name')
RUBY
end

it 'does not registers an offense for `order` with a string argument with DESC direction' do
expect_no_offenses(<<~RUBY)
User.order('1 DESC')
RUBY
end

it 'does not register an offense for `order` with a string argument with ASC order' do
expect_no_offenses(<<~RUBY)
User.order('1 ASC')
RUBY
end
end
end