123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::IfThenCorrector

Relationships & Source Files
Inherits: Object
Defined in: lib/rubocop/cop/correctors/if_then_corrector.rb

Overview

This class autocorrects if…​then structures to a multiline if statement

Constant Summary

Class Method Summary

Instance Attribute Summary

Instance Method Summary

Constructor Details

.new(if_node, indentation: nil) ⇒ IfThenCorrector

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 9

def initialize(if_node, indentation: nil)
  @if_node = if_node
  @indentation = indentation || DEFAULT_INDENTATION_WIDTH
end

Instance Attribute Details

#if_node (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 20

attr_reader :if_node, :indentation

#indentation (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 20

attr_reader :if_node, :indentation

Instance Method Details

#branch_body_indentation (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 50

def branch_body_indentation
  @branch_body_indentation ||= (' ' * indentation).freeze
end

#call(corrector)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 14

def call(corrector)
  corrector.replace(if_node, replacement)
end

#replacement(node = if_node, indentation = nil) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 22

def replacement(node = if_node, indentation = nil)
  indentation = ' ' * node.source_range.column if indentation.nil?
  if_branch_source = node.if_branch&.source || 'nil'
  elsif_indentation = indentation if node.respond_to?(:elsif?) && node.elsif?

  if_branch = <<~RUBY
    #{elsif_indentation}#{node.keyword} #{node.condition.source}
    #{indentation}#{branch_body_indentation}#{if_branch_source}
  RUBY

  else_branch = rewrite_else_branch(node.else_branch, indentation)
  if_branch + else_branch
end

#rewrite_else_branch(else_branch, indentation) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/correctors/if_then_corrector.rb', line 36

def rewrite_else_branch(else_branch, indentation)
  if else_branch.nil?
    'end'
  elsif else_branch.if_type? && else_branch.elsif?
    replacement(else_branch, indentation)
  else
    <<~RUBY.chomp
      #{indentation}else
      #{indentation}#{branch_body_indentation}#{else_branch.source}
      #{indentation}end
    RUBY
  end
end