Sha256: c4c308f247d2296cff4a6d43c767240b438aefb076f5e0cb1818fae3d0c27011

Contents?: true

Size: 1.35 KB

Versions: 12

Compression:

Stored size: 1.35 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_negative_conditional(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

12 entries across 12 versions & 2 rubygems

Version Path
rubyjobbuilderdsl-0.0.2 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/negated_if.rb
rubyjobbuilderdsl-0.0.1 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/negated_if.rb
rubocop-0.30.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.30.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.29.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.29.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.28.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.27.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.27.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.26.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.26.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.25.0 lib/rubocop/cop/style/negated_if.rb