Sha256: 94ce0a124b64adc98cf9c4f910c573bc7cce63edf3d802ba5d0535b97757a13b

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Style
      # Checks for uses of if with a negated condition. Only ifs
      # without else are considered.
      class NegatedIf < Cop
        include NegativeConditional

        MSG = 'Favor `%s` over `%s` for negative conditions.'

        def on_if(node)
          return unless node.loc.respond_to?(:keyword)
          return if node.loc.keyword.is?('elsif')

          check(node)
        end

        def message(node)
          if node.loc.keyword.is?('if')
            format(MSG, 'unless', 'if')
          else
            format(MSG, 'if', 'unless')
          end
        end

        private

        def autocorrect(node)
          @corrections << lambda do |corrector|
            condition, _body, _rest = *node
            # look inside parentheses around the condition
            condition = condition.children.first while condition.type == :begin
            # unwrap the negated portion of the condition (a send node)
            pos_condition, _method, = *condition
            corrector.replace(
              node.loc.keyword,
              node.loc.keyword.is?('if') ? 'unless' : 'if'
            )
            corrector.replace(condition.loc.expression,
                              pos_condition.loc.expression.source)
          end
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubocop-0.22.0 lib/rubocop/cop/style/negated_if.rb