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

autocorrect(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 30
def autocorrect(node)
  lambda do |corrector|
    corrector.replace(node.source_range, to_normal_if(node))
  end
end
on_if(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 24
def on_if(node)
  return unless node.modifier_form? && node.body.multiline?

  add_offense(node)
end

Private Instance Methods

configured_indentation_width() click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 50
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 54
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
message(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 38
def message(node)
  format(MSG, keyword: node.keyword)
end
to_normal_if(node) click to toggle source
# File lib/rubocop/cop/style/multiline_if_modifier.rb, line 42
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