Sha256: 6c0e836e2406e4720aa4184aa889d11161b2c268706295edf720e88c45fd9923

Contents?: true

Size: 1.23 KB

Versions: 11

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # Checks for uses of while with a negated condition.
      class NegatedWhile < Cop
        include NegativeConditional

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

        def on_while(node)
          check_negative_conditional(node)
        end

        def on_until(node)
          check_negative_conditional(node)
        end

        def message(node)
          if node.while_type?
            format(MSG, 'until', 'while')
          else
            format(MSG, 'while', 'until')
          end
        end

        private

        def autocorrect(node)
          lambda do |corrector|
            condition, _body, _rest = *node
            # Look inside parentheses around the condition, if any.
            condition, = *condition while condition.begin_type?
            # Unwrap the negated portion of the condition (a send node).
            pos_condition, _method, = *condition
            corrector.replace(
              node.loc.keyword,
              node.while_type? ? 'until' : 'while'
            )
            corrector.replace(condition.source_range, pos_condition.source)
          end
        end
      end
    end
  end
end

Version data entries

11 entries across 11 versions & 2 rubygems

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