Skip to content

Commit 3064122

Browse files
authored
Merge pull request #1241 from Earlopain/fix-error-for-where-exists
Fix an error for `Rails/WhereExists` with `EnforcedStyle: where` and implicit recievers
2 parents ada5c28 + 80beaf2 commit 3064122

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1241](https://github.com/rubocop/rubocop-rails/pull/1241): Fix an error for `Rails/WhereExists` with `EnforcedStyle: where` and implicit receivers. ([@earlopain][])

lib/rubocop/cop/rails/where_exists.rb

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ def on_send(node)
6767
return unless convertable_args?(args)
6868

6969
range = correction_range(node)
70-
good_method = build_good_method(args, dot_source: node.loc.dot.source)
70+
good_method = build_good_method(args, dot: node.loc.dot)
7171
message = format(MSG, good_method: good_method, bad_method: range.source)
7272

7373
add_offense(range, message: message) do |corrector|
@@ -109,11 +109,11 @@ def correction_range(node)
109109
end
110110
end
111111

112-
def build_good_method(args, dot_source: '.')
112+
def build_good_method(args, dot:)
113113
if exists_style?
114114
build_good_method_exists(args)
115115
elsif where_style?
116-
build_good_method_where(args, dot_source)
116+
build_good_method_where(args, dot&.source || '.')
117117
end
118118
end
119119

spec/rubocop/cop/rails/where_exists_spec.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,17 @@
5959
RUBY
6060
end
6161

62+
it 'registers an offense when using implicit receiver and arg' do
63+
expect_offense(<<~RUBY)
64+
where('name = ?', 'john').exists?
65+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `exists?(['name = ?', 'john'])` over `where('name = ?', 'john').exists?`.
66+
RUBY
67+
68+
expect_correction(<<~RUBY)
69+
exists?(['name = ?', 'john'])
70+
RUBY
71+
end
72+
6273
it 'registers an offense when using `where(...).exists?` with an association' do
6374
expect_offense(<<~RUBY)
6475
user.posts.where(published: true).exists?
@@ -142,6 +153,17 @@
142153
RUBY
143154
end
144155

156+
it 'registers an offense when using implicit receiver and arg' do
157+
expect_offense(<<~RUBY)
158+
exists?('name = ?', 'john')
159+
^^^^^^^^^^^^^^^^^^^^^^^^^^^ Prefer `where('name = ?', 'john').exists?` over `exists?('name = ?', 'john')`.
160+
RUBY
161+
162+
expect_correction(<<~RUBY)
163+
where('name = ?', 'john').exists?
164+
RUBY
165+
end
166+
145167
it 'registers an offense and corrects when using `exists?` with an association' do
146168
expect_offense(<<~RUBY)
147169
user.posts.exists?(published: true)

0 commit comments

Comments
 (0)