Skip to content

Commit

Permalink
Merge pull request #1241 from Earlopain/fix-error-for-where-exists
Browse files Browse the repository at this point in the history
 Fix an error for `Rails/WhereExists` with `EnforcedStyle: where` and implicit recievers
  • Loading branch information
koic committed Feb 26, 2024
2 parents ada5c28 + 80beaf2 commit 3064122
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_error_for_rails_where_exists.md
@@ -0,0 +1 @@
* [#1241](https://github.com/rubocop/rubocop-rails/pull/1241): Fix an error for `Rails/WhereExists` with `EnforcedStyle: where` and implicit receivers. ([@earlopain][])
6 changes: 3 additions & 3 deletions lib/rubocop/cop/rails/where_exists.rb
Expand Up @@ -67,7 +67,7 @@ def on_send(node)
return unless convertable_args?(args)

range = correction_range(node)
good_method = build_good_method(args, dot_source: node.loc.dot.source)
good_method = build_good_method(args, dot: node.loc.dot)
message = format(MSG, good_method: good_method, bad_method: range.source)

add_offense(range, message: message) do |corrector|
Expand Down Expand Up @@ -109,11 +109,11 @@ def correction_range(node)
end
end

def build_good_method(args, dot_source: '.')
def build_good_method(args, dot:)
if exists_style?
build_good_method_exists(args)
elsif where_style?
build_good_method_where(args, dot_source)
build_good_method_where(args, dot&.source || '.')
end
end

Expand Down
22 changes: 22 additions & 0 deletions spec/rubocop/cop/rails/where_exists_spec.rb
Expand Up @@ -59,6 +59,17 @@
RUBY
end

it 'registers an offense when using implicit receiver and arg' do
expect_offense(<<~RUBY)
where('name = ?', 'john').exists?
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `exists?(['name = ?', 'john'])` over `where('name = ?', 'john').exists?`.
RUBY

expect_correction(<<~RUBY)
exists?(['name = ?', 'john'])
RUBY
end

it 'registers an offense when using `where(...).exists?` with an association' do
expect_offense(<<~RUBY)
user.posts.where(published: true).exists?
Expand Down Expand Up @@ -142,6 +153,17 @@
RUBY
end

it 'registers an offense when using implicit receiver and arg' do
expect_offense(<<~RUBY)
exists?('name = ?', 'john')
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `where('name = ?', 'john').exists?` over `exists?('name = ?', 'john')`.
RUBY

expect_correction(<<~RUBY)
where('name = ?', 'john').exists?
RUBY
end

it 'registers an offense and corrects when using `exists?` with an association' do
expect_offense(<<~RUBY)
user.posts.exists?(published: true)
Expand Down

0 comments on commit 3064122

Please sign in to comment.