class RubbyCop::Cop::Style::IfUnlessModifier

Checks for if and unless statements that would fit on one line if written as a modifier if/unless. The maximum line length is configurable.

Constants

ASSIGNMENT_TYPES
MSG

Public Instance Methods

on_if(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 19
def on_if(node)
  return unless eligible_node?(node)

  add_offense(node, :keyword, format(MSG, node.keyword))
end

Private Instance Methods

autocorrect(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 27
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, to_modifier_form(node))
  end
end
eligible_node?(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 33
def eligible_node?(node)
  !non_eligible_if?(node) && !node.chained? &&
    !node.nested_conditional? && single_line_as_modifier?(node)
end
first_line_comment(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 71
def first_line_comment(node)
  comment =
    processed_source.comments.find { |c| c.loc.line == node.loc.line }

  comment ? comment.loc.expression.source : nil
end
method_uses_parens?(node, limit) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 57
def method_uses_parens?(node, limit)
  source = node.source_range.source_line[0...limit.loc.column]
  source =~ /\s*\(\s*$/
end
non_eligible_if?(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 38
def non_eligible_if?(node)
  node.ternary? || node.modifier_form? || node.elsif? || node.else?
end
parenthesize?(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 42
def parenthesize?(node)
  # Parenthesize corrected expression if changing to modifier-if form
  # would change the meaning of the parent expression
  # (due to the low operator precedence of modifier-if)
  return false if node.parent.nil?
  return true if ASSIGNMENT_TYPES.include?(node.parent.type)

  if node.parent.send_type?
    _receiver, _name, *args = *node.parent
    return !method_uses_parens?(node.parent, args.first)
  end

  false
end
to_modifier_form(node) click to toggle source
# File lib/rubbycop/cop/style/if_unless_modifier.rb, line 62
def to_modifier_form(node)
  expression = [node.body.source,
                node.keyword,
                node.condition.source,
                first_line_comment(node)].compact.join(' ')

  parenthesize?(node) ? "(#{expression})" : expression
end