class RuboCop::Cop::Style::AmbiguousEndlessMethodDefinition

Looks for endless methods inside operations of lower precedence (‘and`, `or`, and modifier forms of `if`, `unless`, `while`, `until`) that are ambiguous due to lack of parentheses. This may lead to unexpected behavior as the code may appear to use these keywords as part of the method but in fact they modify the method definition itself.

In these cases, using a normal method definition is more clear.

@example

# bad
def foo = true if bar

# good - using a non-endless method is more explicit
def foo
  true
end if bar

# ok - method body is explicit
def foo = (true if bar)

# ok - method definition is explicit
(def foo = true) if bar

Constants

MSG

Public Instance Methods

on_def(node) click to toggle source
# File lib/rubocop/cop/style/ambiguous_endless_method_definition.rb, line 48
def on_def(node)
  return unless node.endless?

  operation = ambiguous_endless_method_body(node)
  return unless operation

  return unless modifier_form?(operation)

  add_offense(operation, message: format(MSG, keyword: keyword(operation))) do |corrector|
    correct_to_multiline(corrector, node)
  end
end

Private Instance Methods

keyword(operation) click to toggle source
# File lib/rubocop/cop/style/ambiguous_endless_method_definition.rb, line 69
def keyword(operation)
  if operation.respond_to?(:keyword)
    operation.keyword
  else
    operation.operator
  end
end
modifier_form?(operation) click to toggle source
# File lib/rubocop/cop/style/ambiguous_endless_method_definition.rb, line 63
def modifier_form?(operation)
  return true if operation.and_type? || operation.or_type?

  operation.modifier_form?
end