Sha256: bd8c00945147a230590854af5c05f2e904f893d9800f649ff7e396ae087f281e

Contents?: true

Size: 1.58 KB

Versions: 6

Compression:

Stored size: 1.58 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # 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
      class MultilineIfModifier < Cop
        include StatementModifier
        include AutocorrectAlignment

        MSG = 'Favor a normal %s-statement over a modifier' \
              ' clause in a multiline statement.'.freeze

        def on_if(node)
          return unless node.modifier_form? && node.body.multiline?

          add_offense(node, :expression, format(MSG, node.keyword))
        end

        private

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node.source_range, to_normal_if(node))
          end
        end

        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

        def configured_indentation_width
          super || 2
        end

        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
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rubocop-0.49.1 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.49.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.48.1 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.48.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.47.1 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.47.0 lib/rubocop/cop/style/multiline_if_modifier.rb