Sha256: 9a3cb948ee3a29304e05f0680c0a42ce2343749312b3cee2b53b58a3519d5767

Contents?: true

Size: 1.3 KB

Versions: 9

Compression:

Stored size: 1.3 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # Use `Kernel#loop` for infinite loops.
      #
      # @example
      #   # bad
      #   while true
      #     work
      #   end
      #
      #   # good
      #   loop do
      #     work
      #   end
      class InfiniteLoop < Cop
        MSG = 'Use `Kernel#loop` for infinite loops.'

        TRUTHY_LITERALS = [:str, :dstr, :int, :float, :array,
                           :hash, :regexp, :true]

        FALSEY_LITERALS = [:nil, :false]

        def on_while(node)
          condition, = *node

          return unless TRUTHY_LITERALS.include?(condition.type)

          add_offense(node, :keyword)
        end

        def on_until(node)
          condition, = *node

          return unless FALSEY_LITERALS.include?(condition.type)

          add_offense(node, :keyword)
        end

        def autocorrect(node)
          condition_node, = *node
          start_range = node.loc.keyword.begin
          end_range = if node.loc.begin
                        node.loc.begin.end
                      else
                        condition_node.loc.expression.end
                      end
          lambda do |corrector|
            corrector.replace(start_range.join(end_range), 'loop do')
          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/infinite_loop.rb
rubocop-0.35.0 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.34.2 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.34.1 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.34.0 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.33.0 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.32.1 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.32.0 lib/rubocop/cop/style/infinite_loop.rb
rubocop-0.31.0 lib/rubocop/cop/style/infinite_loop.rb