class RuboCop::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 configured in the `Metrics/LineLength` cop. The tab size is configured in the `IndentationWidth` of the `Layout/Tab` cop.

@example

# bad
if condition
  do_stuff(bar)
end

unless qux.empty?
  Foo.do_something
end

# good
do_stuff(bar) if condition
Foo.do_something unless qux.empty?

Constants

ASSIGNMENT_TYPES
MSG

Public Instance Methods

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 42
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, to_modifier_form(node))
  end
end
on_if(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 34
def on_if(node)
  return unless eligible_node?(node)
  return if named_capture_in_condition?(node)

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

Private Instance Methods

eligible_node?(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 54
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/rubocop/cop/style/if_unless_modifier.rb, line 82
def first_line_comment(node)
  comment =
    processed_source.find_comment { |c| c.loc.line == node.loc.line }

  comment ? comment.loc.expression.source : nil
end
named_capture_in_condition?(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 50
def named_capture_in_condition?(node)
  node.condition.match_with_lvasgn_type?
end
non_eligible_if?(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 59
def non_eligible_if?(node)
  node.ternary? || node.modifier_form? || node.elsif? || node.else?
end
parenthesize?(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 63
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)

  node.parent.send_type? && !node.parent.parenthesized?
end
to_modifier_form(node) click to toggle source
# File lib/rubocop/cop/style/if_unless_modifier.rb, line 73
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