Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix an error for Rails/UniqBeforePluck with EnforcedStyle: aggressive when no receiver #1255

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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