rubocop-rails icon indicating copy to clipboard operation
rubocop-rails copied to clipboard

Cop request: private delegates

Open Drenmi opened this issue 4 years ago • 4 comments

Is your feature request related to a problem? Please describe.

When using #delegate, ActiveSupport creates a new method on the class, but this method does not respect the visibility scope of said class.

For example:

class Foo
  def initialize(bar)
    @bar = bar
  end

  attr_reader :bar

  private

  delegate :baz, to: :bar
end

The generated method #baz will not be private. The #delegate method does, however, provide an option to create a private method like so:

delegate :baz, to: :bar, private: true

Describe the solution you'd like

I would like a cop that detects calls to #delegate that:

  1. Are in a private scope.
  2. Does not pass the private: true option.

Drenmi avatar Oct 09 '20 07:10 Drenmi

Sidenote: The private option was added in Rails 6: https://blog.bigbinary.com/2019/06/10/rails-6-adds-private-option-to-delegate-method.html

andyw8 avatar Oct 10 '20 17:10 andyw8

I've had the same desire and would like to build this feature!

is it okay if I go ahead and start working on it following the contribution guidelines? or is there any other protocol to follow up on?

ABaldwinHunter avatar May 06 '22 20:05 ABaldwinHunter

@ABaldwinHunter go ahead! See https://github.com/rubocop/rubocop-rails/blob/master/CONTRIBUTING.md

andyw8 avatar May 06 '22 22:05 andyw8

I started working on this. But what to do (in terms of auto-correction) when private option is passed, but there is mismatch in the scope? E.g.

class A
  private

  delegate :bar, to: :foo, private: false
class B
  public

  delegate :bar, to: :foo, private: true

Should we instead of changing the private option, move the node? Or register an offense with a different message (than in the missing private option) and do not attempt to auto-correct?

Darhazer avatar Jul 14 '22 22:07 Darhazer