Sha256: 3853362f6b7e7f9ef8124a5e26692042ca7b24295db322a5e8945b3b3f6fa177

Contents?: true

Size: 1.39 KB

Versions: 13

Compression:

Stored size: 1.39 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop looks for uses of the *for* keyword, or *each* method. The
      # preferred alternative is set in the EnforcedStyle configuration
      # parameter. An *each* call with a block on a single line is always
      # allowed, however.
      class For < Cop
        include ConfigurableEnforcedStyle
        EACH_LENGTH = 'each'.length

        def on_for(node)
          if style == :each
            add_offense(node, :keyword, 'Prefer `each` over `for`.') do
              opposite_style_detected
            end
          else
            correct_style_detected
          end
        end

        def on_block(node)
          return if block_length(node).zero?

          method, _args, _body = *node
          return unless method.send_type?

          _receiver, method_name, *args = *method
          return unless method_name == :each && args.empty?

          if style == :for
            incorrect_style_detected(method)
          else
            correct_style_detected
          end
        end

        private

        def incorrect_style_detected(method)
          end_pos = method.source_range.end_pos
          range = range_between(end_pos - EACH_LENGTH, end_pos)
          add_offense(range, range, 'Prefer `for` over `each`.') do
            opposite_style_detected
          end
        end
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

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