Class: RuboCop::Cop::Rails::Delegate

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
VisibilityHelp
Defined in:
lib/rubocop/cop/rails/delegate.rb

Overview

Looks for delegations that could have been created automatically with the ‘delegate` method.

Safe navigation ‘&.` is ignored because Rails’ ‘allow_nil` option checks not just for nil but also delegates if nil responds to the delegated method.

The ‘EnforceForPrefixed` option (defaulted to `true`) means that using the target object as a prefix of the method name without using the `delegate` method will be a violation. When set to `false`, this case is legal.

Examples:

# bad
def bar
  foo.bar
end

# good
delegate :bar, to: :foo

# bad
def bar
  self.bar
end

# good
delegate :bar, to: :self

# good
def bar
  foo&.bar
end

# good
private
def bar
  foo.bar
end

EnforceForPrefixed: true (default)

# bad
def foo_bar
  foo.bar
end

# good
delegate :bar, to: :foo, prefix: true

EnforceForPrefixed: false

# good
def foo_bar
  foo.bar
end

# good
delegate :bar, to: :foo, prefix: true

Constant Summary collapse

MSG =
'Use `delegate` to define delegations.'

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object



74
75
76
77
78
79
# File 'lib/rubocop/cop/rails/delegate.rb', line 74

def on_def(node)
  return unless trivial_delegate?(node)
  return if private_or_protected_delegation(node)

  register_offense(node)
end