Skip to content

Commit

Permalink
Merge pull request #1330 from Earlopain/where-not-error
Browse files Browse the repository at this point in the history
Fix an error for `Rails/WhereNot` without second argument
  • Loading branch information
koic authored Aug 15, 2024
2 parents d4a4ea7 + 26b18c5 commit b676624
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 b676624

Please sign in to comment.