Skip to content

Commit

Permalink
Merge pull request #1235 from ymap/fix_an_incorrect_autocorrect_for_r…
Browse files Browse the repository at this point in the history
…ails_find_by

[Fix #1234] Fix an incorrect autocorrect for `Rails/FindBy`
  • Loading branch information
koic committed Feb 1, 2024
2 parents aa3fc59 + 6b9568c commit 8293b58
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +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][])
2 changes: 1 addition & 1 deletion lib/rubocop/cop/rails/find_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def autocorrect(corrector, node)
return if node.method?(:first)

where_loc = node.receiver.loc.selector
first_loc = range_between(node.loc.dot.begin_pos, node.loc.selector.end_pos)
first_loc = range_between(node.receiver.source_range.end_pos, node.loc.selector.end_pos)

corrector.replace(where_loc, 'find_by')
corrector.replace(first_loc, '')
Expand Down
28 changes: 28 additions & 0 deletions spec/rubocop/cop/rails/find_by_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,34 @@
RUBY
end

it 'registers and corrects an offense when using multi-line leading dot method calls' do
expect_offense(<<~RUBY)
User
.where(id: x)
^^^^^^^^^^^^ Use `find_by` instead of `where.take`.
.take
RUBY

expect_correction(<<~RUBY)
User
.find_by(id: x)
RUBY
end

it 'registers and corrects an offense when using multi-line trailing dot method calls' do
expect_offense(<<~RUBY)
User.
where(id: x).
^^^^^^^^^^^^^ Use `find_by` instead of `where.take`.
take
RUBY

expect_correction(<<~RUBY)
User.
find_by(id: x)
RUBY
end

context 'when using safe navigation operator' do
it 'registers an offense when using `#take`' do
expect_offense(<<~RUBY)
Expand Down

0 comments on commit 8293b58

Please sign in to comment.