class RuboCop::Cop::Style::MultilineIfModifier

Checks for uses of if/unless modifiers with multiple-lines bodies.

@example

# bad
{
  result: 'this should not happen'
} unless cond

# good
{ result: 'ok' } if cond

Constants

MSG

Public Instance Methods

on_if(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 25
def on_if(node)
  return unless node.modifier_form? && node.body.multiline?

  add_offense(node, message: format(MSG, keyword: node.keyword)) do |corrector|
    corrector.replace(node, to_normal_if(node))
  end
end

Private Instance Methods

configured_indentation_width() click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 43
def configured_indentation_width
  super || 2
end
indented_body(body, node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 47
def indented_body(body, node)
  body_source = "#{offset(node)}#{body.source}"
  body_source.each_line.map do |line|
    if line == "\n"
      line
    else
      line.sub(/^\s{#{offset(node).length}}/, indentation(node))
    end
  end.join
end
to_normal_if(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 35
def to_normal_if(node)
  indented_body = indented_body(node.body, node)
  condition = "#{node.keyword} #{node.condition.source}"
  indented_end = "#{offset(node)}end"

  [condition, indented_body, indented_end].join("\n")
end