From b849c6052c1f7bd18daf09cbecd89600d74fbc31 Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Fri, 15 Mar 2024 20:01:46 +0100 Subject: [PATCH] Fix an error for `Rails/UniqBeforePluck` with `EnforcedStyle: aggressive` when no receiver --- .../fix_an_error_for_rails_uniq_before_pluck.md | 1 + lib/rubocop/cop/rails/uniq_before_pluck.rb | 16 ++++++++++++---- spec/rubocop/cop/rails/uniq_before_pluck_spec.rb | 11 +++++++++++ 3 files changed, 24 insertions(+), 4 deletions(-) create mode 100644 changelog/fix_an_error_for_rails_uniq_before_pluck.md diff --git a/changelog/fix_an_error_for_rails_uniq_before_pluck.md b/changelog/fix_an_error_for_rails_uniq_before_pluck.md new file mode 100644 index 0000000000..abbd91d7ae --- /dev/null +++ b/changelog/fix_an_error_for_rails_uniq_before_pluck.md @@ -0,0 +1 @@ +* [#1255](https://github.com/rubocop/rubocop-rails/pull/1255): Fix an error for `Rails/UniqBeforePluck` with `EnforcedStyle: aggressive` when no receiver. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/uniq_before_pluck.rb b/lib/rubocop/cop/rails/uniq_before_pluck.rb index 91caf5506d..d11c8569e7 100644 --- a/lib/rubocop/cop/rails/uniq_before_pluck.rb +++ b/lib/rubocop/cop/rails/uniq_before_pluck.rb @@ -68,15 +68,23 @@ def on_send(node) return unless uniq add_offense(node.loc.selector) do |corrector| - method = node.method_name - - corrector.remove(dot_method_with_whitespace(method, node)) - corrector.insert_before(node.receiver.loc.dot.begin, '.distinct') + autocorrect(corrector, node) end end private + def autocorrect(corrector, node) + method = node.method_name + + corrector.remove(dot_method_with_whitespace(method, node)) + if (dot = node.receiver.loc.dot) + corrector.insert_before(dot.begin, '.distinct') + else + corrector.insert_before(node.receiver, 'distinct.') + end + end + def dot_method_with_whitespace(method, node) range_between(dot_method_begin_pos(method, node), node.loc.selector.end_pos) end diff --git a/spec/rubocop/cop/rails/uniq_before_pluck_spec.rb b/spec/rubocop/cop/rails/uniq_before_pluck_spec.rb index 4cf9688b1e..7ba2a9616c 100644 --- a/spec/rubocop/cop/rails/uniq_before_pluck_spec.rb +++ b/spec/rubocop/cop/rails/uniq_before_pluck_spec.rb @@ -113,5 +113,16 @@ instance.assoc.distinct.pluck(:name) RUBY end + + it 'corrects uniq when used without a receiver' do + expect_offense(<<~RUBY) + pluck(:name).uniq + ^^^^ Use `distinct` before `pluck`. + RUBY + + expect_correction(<<~RUBY) + distinct.pluck(:name) + RUBY + end end end