Class: RuboCop::Cop::Tablecop::SafeEndlessMethod

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Defined in:
lib/rubocop/cop/tablecop/safe_endless_method.rb

Overview

Converts multi-line single-expression methods to single-line form.

Uses endless method syntax (‘def foo = expr`) for simple cases, but falls back to traditional one-liner (`def foo() expr end`) for methods with modifier-if/unless that call other methods (which can fail in module_eval contexts or at parse time).

This cop avoids the bugs in RuboCop’s Style/EndlessMethod:

  • Heredoc destruction

  • Rescue clause orphaning

  • module_eval context failures

  • Modifier-if with dynamic method failures

Examples:

Endless method (safe)

# bad
def foo
  42
end

# good
def foo = 42

Traditional one-liner (modifier-if with method call)

# bad
def clear!
  data_layer.clear! if data_layer.respond_to?(:clear!)
end

# good
def clear!() data_layer.clear! if data_layer.respond_to?(:clear!) end

Constant Summary collapse

MSG_ENDLESS =
"Use endless method: `def %<name>s%<args>s = %<body>s`"
MSG_TRADITIONAL =
"Use single-line method: `def %<name>s%<args>s %<body>s end`"

Instance Method Summary collapse

Instance Method Details

#on_def(node) ⇒ Object Also known as: on_defs



43
44
45
46
47
48
49
50
51
# File 'lib/rubocop/cop/tablecop/safe_endless_method.rb', line 43

def on_def(node)
  return unless convertible?(node)

  if should_use_traditional?(node)
    register_traditional_offense(node)
  else
    register_endless_offense(node)
  end
end