Skip to content

Commit

Permalink
[Fix rubocop#1234] Fix an incorrect autocorrect for Rails/FindBy
Browse files Browse the repository at this point in the history
Fixes rubocop#1234.

This PR fixes an incorrect autocorrect for `Rails/FindBy`
when using multi-line leading dot method calls.
  • Loading branch information
ymap committed Feb 1, 2024
1 parent aa3fc59 commit 99e19da
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
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][])
3 changes: 1 addition & 2 deletions lib/rubocop/cop/rails/find_by.rb
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +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, '')
end
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 99e19da

Please sign in to comment.