Sha256: d7509f549a59e84bee79c47c2e7d9318460996392e73cb25e10c3c0e2c133159

Contents?: true

Size: 1.32 KB

Versions: 13

Compression:

Stored size: 1.32 KB

Contents

# encoding: utf-8
# frozen_string_literal: true

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.'.freeze

        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)
          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.source_range, pos_condition.source)
          end
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
fluent-plugin-detect-memb-exceptions-0.0.2 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/style/negated_if.rb
fluent-plugin-detect-memb-exceptions-0.0.1 vendor/bundle/ruby/2.0.0/gems/rubocop-0.42.0/lib/rubocop/cop/style/negated_if.rb
rubocop-0.42.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.41.2 lib/rubocop/cop/style/negated_if.rb
rubocop-0.41.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.41.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.40.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.39.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.38.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.37.2 lib/rubocop/cop/style/negated_if.rb
rubocop-0.37.1 lib/rubocop/cop/style/negated_if.rb
rubocop-0.37.0 lib/rubocop/cop/style/negated_if.rb
rubocop-0.36.0 lib/rubocop/cop/style/negated_if.rb