Sha256: 5f847d6c604534d02453ce1711da8509f0178ef9c7c52096ee1d5200bbaf8212

Contents?: true

Size: 1.25 KB

Versions: 9

Compression:

Stored size: 1.25 KB

Contents

# encoding: utf-8

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

        def on_while(node)
          check_negative_conditional(node)
        end

        def on_until(node)
          check_negative_conditional(node)
        end

        def message(node)
          if node.type == :while
            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.type == :begin
            # Unwrap the negated portion of the condition (a send node).
            pos_condition, _method, = *condition
            corrector.replace(
              node.loc.keyword,
              node.type == :while ? 'until' : 'while')
            corrector.replace(condition.loc.expression,
                              pos_condition.loc.expression.source)
          end
        end
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
rubocop-0.35.1 lib/rubocop/cop/style/negated_while.rb
rubocop-0.35.0 lib/rubocop/cop/style/negated_while.rb
rubocop-0.34.2 lib/rubocop/cop/style/negated_while.rb
rubocop-0.34.1 lib/rubocop/cop/style/negated_while.rb
rubocop-0.34.0 lib/rubocop/cop/style/negated_while.rb
rubocop-0.33.0 lib/rubocop/cop/style/negated_while.rb
rubocop-0.32.1 lib/rubocop/cop/style/negated_while.rb
rubocop-0.32.0 lib/rubocop/cop/style/negated_while.rb
rubocop-0.31.0 lib/rubocop/cop/style/negated_while.rb