From 6b9568ca40e16aebebef5157324b876c95f278d5 Mon Sep 17 00:00:00 2001 From: ymap Date: Thu, 1 Feb 2024 00:37:05 +0000 Subject: [PATCH] [Fix #1234] Fix an incorrect autocorrect for `Rails/FindBy` Fixes #1234. This PR fixes an incorrect autocorrect for `Rails/FindBy` when using multi-line leading dot method calls. --- ...incorrect_autocorrect_for_rails_find_by.md | 1 + lib/rubocop/cop/rails/find_by.rb | 2 +- spec/rubocop/cop/rails/find_by_spec.rb | 28 +++++++++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_an_incorrect_autocorrect_for_rails_find_by.md diff --git a/changelog/fix_an_incorrect_autocorrect_for_rails_find_by.md b/changelog/fix_an_incorrect_autocorrect_for_rails_find_by.md new file mode 100644 index 0000000000..bfa6a776e1 --- /dev/null +++ b/changelog/fix_an_incorrect_autocorrect_for_rails_find_by.md @@ -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][]) diff --git a/lib/rubocop/cop/rails/find_by.rb b/lib/rubocop/cop/rails/find_by.rb index 28ad3200ef..d74ca88e08 100644 --- a/lib/rubocop/cop/rails/find_by.rb +++ b/lib/rubocop/cop/rails/find_by.rb @@ -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, '') diff --git a/spec/rubocop/cop/rails/find_by_spec.rb b/spec/rubocop/cop/rails/find_by_spec.rb index ecf64ffb3b..61da4a68b8 100644 --- a/spec/rubocop/cop/rails/find_by_spec.rb +++ b/spec/rubocop/cop/rails/find_by_spec.rb @@ -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)