Rubocop: [BUG] Use uniq before pluck

Created on 19 May 2016  路  6Comments  路  Source: rubocop-hq/rubocop

In model i have

  def events_ids
    result = volunteer_roles.uniq.pluck(:event_id)
    result.any? ? result : nil
  end

rubocop -a returns

Offenses:

app/models/user.rb:157:47: C: [Corrected] Use uniq before pluck
    result = volunteer_roles.pluck(:event_id).uniq
                                              ^^^^

And in this case, it is wrong correction, because uniq or distinct methods return Array and pluck need Activerecord::Relation

Most helpful comment

I don't think we can easily distinguish between uniq being called on CollectionProxy vs an ActiveRecord::Relation :(

I should either:

  1. Make this cop disabled by default, remove autocorrection, and comment on when it may give a false positive. The cop has been useful for us, and may be helpful for others that do not typically use uniq or distinct on associations.
  2. Remove the cop. I expect we'll continue to use it, but I'll just move it to a custom cop in our code.

Let me know what is preferred in situations like this.

All 6 comments

@tjwp?

I cannot replay it now, but as I see it is closed :+1:

This is not fixed and should be reopened.

See: https://github.com/bbatsov/rubocop/issues/3122#issuecomment-218126545

I agree. It's not fixed.

I don't think we can easily distinguish between uniq being called on CollectionProxy vs an ActiveRecord::Relation :(

I should either:

  1. Make this cop disabled by default, remove autocorrection, and comment on when it may give a false positive. The cop has been useful for us, and may be helpful for others that do not typically use uniq or distinct on associations.
  2. Remove the cop. I expect we'll continue to use it, but I'll just move it to a custom cop in our code.

Let me know what is preferred in situations like this.

Maybe we can still "save" this cop by making it more conservative. I mean, we could start with some simple expressions that we believe will not generate many false positives. For example:

MyModel.pluck(:col).uniq

where the receiver looks like a class. We let the cop only report such expressions.

But even so, removing (or disabling) auto-correct might be necessary.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

NobodysNightmare picture NobodysNightmare  路  3Comments

david942j picture david942j  路  3Comments

herwinw picture herwinw  路  3Comments

mlammers picture mlammers  路  3Comments

Aqualon picture Aqualon  路  3Comments