Sha256: ed0ad82c79523229f775c97f3e812dcd8635c9d6d3fd91d556507f61f8521ed5

Contents?: true

Size: 1.63 KB

Versions: 6790

Compression:

Stored size: 1.63 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 Alignment

        MSG = 'Favor a normal %<keyword>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)
        end

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

        private

        def message(node)
          format(MSG, keyword: node.keyword)
        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,790 entries across 6,784 versions & 25 rubygems

Version Path
rubocop-0.58.0 lib/rubocop/cop/style/multiline_if_modifier.rb
vagrant-packet-0.1.1 vendor/bundle/ruby/2.4.0/gems/rubocop-0.57.2/lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.57.2 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.57.1 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.57.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.56.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.55.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.54.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.53.0 lib/rubocop/cop/style/multiline_if_modifier.rb
rubocop-0.52.1 lib/rubocop/cop/style/multiline_if_modifier.rb