class RuboCop::Cop::Style::EndlessMethod

Checks for endless methods.

It can enforce either the use of endless methods definitions for single-lined method bodies, or disallow endless methods.

Other method definition types are not considered by this cop.

The supported styles are:

NOTE: Incorrect endless method definitions will always be corrected to a multi-line definition.

@example EnforcedStyle: allow_single_line (default)

# good
def my_method() = x

# bad, multi-line endless method
def my_method() = x.foo
                   .bar
                   .baz

@example EnforcedStyle: allow_always

# good
def my_method() = x

# good
def my_method() = x.foo
                   .bar
                   .baz

@example EnforcedStyle: disallow

# bad
def my_method() = x

# bad
def my_method() = x.foo
                   .bar
                   .baz

Constants

CORRECTION_STYLES
MSG
MSG_MULTI_LINE

Public Instance Methods

on_def(node) click to toggle source
# File lib/rubocop/cop/style/endless_method.rb, line 60
def on_def(node)
  if style == :disallow
    handle_disallow_style(node)
  else
    handle_allow_style(node)
  end
end

Private Instance Methods

arguments(node, missing = '') click to toggle source
# File lib/rubocop/cop/style/endless_method.rb, line 95
def arguments(node, missing = '')
  node.arguments.any? ? node.arguments.source : missing
end
correct_to_multiline(corrector, node) click to toggle source
# File lib/rubocop/cop/style/endless_method.rb, line 85
        def correct_to_multiline(corrector, node)
          replacement = <<~RUBY.strip
            def #{node.method_name}#{arguments(node)}
              #{node.body.source}
            end
          RUBY

          corrector.replace(node, replacement)
        end
handle_allow_style(node) click to toggle source
# File lib/rubocop/cop/style/endless_method.rb, line 70
def handle_allow_style(node)
  return unless node.endless?
  return if node.single_line? || style == :allow_always

  add_offense(node, message: MSG_MULTI_LINE) do |corrector|
    correct_to_multiline(corrector, node)
  end
end
handle_disallow_style(node) click to toggle source
# File lib/rubocop/cop/style/endless_method.rb, line 79
def handle_disallow_style(node)
  return unless node.endless?

  add_offense(node) { |corrector| correct_to_multiline(corrector, node) }
end