Skip to content

Commit 17c2831

Browse files
authored
Merge pull request #1510 from viralpraxis/fix-rails-order-arguments-cop-false-positives
Fix `Rails/OrderArguments` cop false positives
2 parents 812251d + 3971a35 commit 17c2831

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1510](https://github.com/rubocop/rubocop-rails/pull/1510): Fix `Rails/OrderArguments` cop false positives when using column index argument. ([@viralpraxis][])

lib/rubocop/cop/rails/order_arguments.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ def replacement(order_expressions)
5252
order_arguments.map! { |arg| extract_column_and_direction(arg.strip) }
5353

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

5657
convert_to_preferred_arguments(order_arguments).join(', ')
5758
end
@@ -68,6 +69,10 @@ def convert_to_preferred_arguments(order_expressions)
6869
end
6970
end
7071

72+
def positional_column?(column_name)
73+
column_name.match?(/\A\d+\z/)
74+
end
75+
7176
def extract_column_and_direction(order_expression)
7277
return unless (column, direction = ORDER_EXPRESSION_REGEX.match(order_expression)&.captures)
7378

spec/rubocop/cop/rails/order_arguments_spec.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,4 +128,30 @@
128128
User.order('LEFT(first_name, 1)')
129129
RUBY
130130
end
131+
132+
context 'with numeric string literal column name' do
133+
it 'does not register an offense for `order` with a string argument' do
134+
expect_no_offenses(<<~RUBY)
135+
User.order('1')
136+
RUBY
137+
end
138+
139+
it 'does not register an offense for `order` with multiple string arguments' do
140+
expect_no_offenses(<<~RUBY)
141+
User.order('1', 'last_name')
142+
RUBY
143+
end
144+
145+
it 'does not registers an offense for `order` with a string argument with DESC direction' do
146+
expect_no_offenses(<<~RUBY)
147+
User.order('1 DESC')
148+
RUBY
149+
end
150+
151+
it 'does not register an offense for `order` with a string argument with ASC order' do
152+
expect_no_offenses(<<~RUBY)
153+
User.order('1 ASC')
154+
RUBY
155+
end
156+
end
131157
end

0 commit comments

Comments
 (0)