Skip to content

Commit 8293b58

Browse files
authored
Merge pull request #1235 from ymap/fix_an_incorrect_autocorrect_for_rails_find_by
[Fix #1234] Fix an incorrect autocorrect for `Rails/FindBy`
2 parents aa3fc59 + 6b9568c commit 8293b58

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
* [#1234](https://github.com/rubocop/rubocop-rails/issues/1234): Fix an incorrect autocorrect for `Rails/FindBy` when using multi-line leading dot method calls. ([@ymap][])

lib/rubocop/cop/rails/find_by.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def autocorrect(corrector, node)
5959
return if node.method?(:first)
6060

6161
where_loc = node.receiver.loc.selector
62-
first_loc = range_between(node.loc.dot.begin_pos, node.loc.selector.end_pos)
62+
first_loc = range_between(node.receiver.source_range.end_pos, node.loc.selector.end_pos)
6363

6464
corrector.replace(where_loc, 'find_by')
6565
corrector.replace(first_loc, '')

spec/rubocop/cop/rails/find_by_spec.rb

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,34 @@
3434
RUBY
3535
end
3636

37+
it 'registers and corrects an offense when using multi-line leading dot method calls' do
38+
expect_offense(<<~RUBY)
39+
User
40+
.where(id: x)
41+
^^^^^^^^^^^^ Use `find_by` instead of `where.take`.
42+
.take
43+
RUBY
44+
45+
expect_correction(<<~RUBY)
46+
User
47+
.find_by(id: x)
48+
RUBY
49+
end
50+
51+
it 'registers and corrects an offense when using multi-line trailing dot method calls' do
52+
expect_offense(<<~RUBY)
53+
User.
54+
where(id: x).
55+
^^^^^^^^^^^^^ Use `find_by` instead of `where.take`.
56+
take
57+
RUBY
58+
59+
expect_correction(<<~RUBY)
60+
User.
61+
find_by(id: x)
62+
RUBY
63+
end
64+
3765
context 'when using safe navigation operator' do
3866
it 'registers an offense when using `#take`' do
3967
expect_offense(<<~RUBY)

0 commit comments

Comments
 (0)