Skip to content

Commit

Permalink
Fix an error for Rails/WhereNot without second argument
Browse files Browse the repository at this point in the history
This is basically rubocop#401 again, and a bit of rubocop#1321
  • Loading branch information
Earlopain authored and koic committed Aug 23, 2024
1 parent 1fde891 commit 17a036f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions changelog/fix_error_rails_where_not_no_second_argument.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* [#1330](https://github.com/rubocop/rubocop-rails/pull/1330): Fix an error for `Rails/WhereNot` when using placeholder without second argument. ([@earlopain][])
10 changes: 5 additions & 5 deletions lib/rubocop/cop/rails/where_not.rb
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ def on_send(node)

range = offense_range(node)

column_and_value = extract_column_and_value(template_node, value_node)
return unless column_and_value
column, value = extract_column_and_value(template_node, value_node)
return unless value

good_method = build_good_method(node.loc.dot&.source, *column_and_value)
good_method = build_good_method(node.loc.dot&.source, column, value)
message = format(MSG, good_method: good_method)

add_offense(range, message: message) do |corrector|
Expand All @@ -72,9 +72,9 @@ def extract_column_and_value(template_node, value_node)
value =
case template_node.value
when NOT_EQ_ANONYMOUS_RE, NOT_IN_ANONYMOUS_RE
value_node.source
value_node&.source
when NOT_EQ_NAMED_RE, NOT_IN_NAMED_RE
return unless value_node.hash_type?
return unless value_node&.hash_type?

pair = value_node.pairs.find { |p| p.key.value.to_sym == Regexp.last_match(2).to_sym }
pair.value.source
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/rails/where_not_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@
RUBY
end

it 'registers no offense when using `!=` and anonymous placeholder without second argument' do
expect_no_offenses(<<~RUBY)
User.where('name != ?')
RUBY
end

it 'registers an offense and corrects when using `!=` and anonymous placeholder with safe navigation' do
expect_offense(<<~RUBY)
User&.where('name != ?', 'Gabe')
Expand Down Expand Up @@ -89,6 +95,12 @@
RUBY
end

it 'registers no offense when using `NOT IN` and named placeholder without second argument' do
expect_no_offenses(<<~RUBY)
User.where("name NOT IN (:names)")
RUBY
end

it 'registers an offense and corrects when using `!=` and namespaced columns' do
expect_offense(<<~RUBY)
Course.where('enrollments.student_id != ?', student.id)
Expand Down

0 comments on commit 17a036f

Please sign in to comment.