Sha256: 1989ad441d907146f48a23afffe11b37feeb3e697456cb4cbb20fb423f808d22

Contents?: true

Size: 1.76 KB

Versions: 9

Compression:

Stored size: 1.76 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 IfNode
        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 modifier_if?(node)

          _cond, body = if_node_parts(node)
          return if body.single_line?

          add_offense(node, :expression)
        end

        private

        def message(node)
          format(MSG, node.loc.keyword.source)
        end

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

        def to_normal_if(node)
          cond, body = if_node_parts(node)
          indented_body = indented_body(body, node)

          condition = "#{node.loc.keyword.source} #{cond.source}"
          indented_end = "#{offset(node)}end"

          "#{condition}\n#{indented_body}\n#{indented_end}"
        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

9 entries across 9 versions & 2 rubygems

Version Path
dirwatch-0.0.9 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.8 vendor/bundle/ruby/2.5.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.6 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.5 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.4 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.3 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
dirwatch-0.0.2 vendor/bundle/ruby/2.3.0/gems/rubocop-0.46.0/lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.46.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.45.0 lib/rubocop/cop/style/multiline_if_modifier.rb