class RuboCop::Cop::IfThenCorrector

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

Constants

DEFAULT_INDENTATION_WIDTH

Attributes

if_node[R]
indentation[R]

Public Class Methods

new(if_node, indentation: nil) click to toggle source
# 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

Public Instance Methods

call(corrector) click to toggle source
# File lib/rubocop/cop/correctors/if_then_corrector.rb, line 14
def call(corrector)
  corrector.replace(if_node, replacement)
end

Private Instance Methods

branch_body_indentation() click to toggle source
# File lib/rubocop/cop/correctors/if_then_corrector.rb, line 50
def branch_body_indentation
  @branch_body_indentation ||= (' ' * indentation).freeze
end
replacement(node = if_node, indentation = nil) click to toggle source
# 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) click to toggle source
# 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