Skip to content

Commit

Permalink
Merge pull request #1255 from Earlopain/fix-error-for-rails-unique-be…
Browse files Browse the repository at this point in the history
…fore-pluck

Fix an error for `Rails/UniqBeforePluck` with `EnforcedStyle: aggressive` when no receiver
  • Loading branch information
koic committed Mar 22, 2024
2 parents 650e783 + b849c60 commit af30389
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 4 deletions.
1 change: 1 addition & 0 deletions 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][])
16 changes: 12 additions & 4 deletions lib/rubocop/cop/rails/uniq_before_pluck.rb
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions spec/rubocop/cop/rails/uniq_before_pluck_spec.rb
Expand Up @@ -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

0 comments on commit af30389

Please sign in to comment.