Sha256: 322086737200fed48aa48f5dab34c91a9b91efbed2dae07766a0c64fadc1e751

Contents?: true

Size: 1.42 KB

Versions: 15

Compression:

Stored size: 1.42 KB

Contents

# frozen_string_literal: true

module RuboCop
  module Cop
    module Style
      # This cop checks for places where `Integer#even?` or `Integer#odd?`
      # can be used.
      #
      # @example
      #
      #   # bad
      #   if x % 2 == 0
      #   end
      #
      #   # good
      #   if x.even?
      #   end
      class EvenOdd < Cop
        MSG = 'Replace with `Integer#%<method>s?`.'

        def_node_matcher :even_odd_candidate?, <<~PATTERN
          (send
            {(send $_ :% (int 2))
             (begin (send $_ :% (int 2)))}
            ${:== :!=}
            (int ${0 1}))
        PATTERN

        def on_send(node)
          even_odd_candidate?(node) do |_base_number, method, arg|
            replacement_method = replacement_method(arg, method)
            add_offense(node, message: format(MSG, method: replacement_method))
          end
        end

        def autocorrect(node)
          even_odd_candidate?(node) do |base_number, method, arg|
            replacement_method = replacement_method(arg, method)

            correction = "#{base_number.source}.#{replacement_method}?"
            ->(corrector) { corrector.replace(node, correction) }
          end
        end

        private

        def replacement_method(arg, method)
          case arg
          when 0
            method == :== ? :even : :odd
          when 1
            method == :== ? :odd : :even
          end
        end
      end
    end
  end
end

Version data entries

15 entries across 15 versions & 3 rubygems

Version Path
rubocop-0.89.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.88.0 lib/rubocop/cop/style/even_odd.rb
rbhint-0.87.1.rc1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.87.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.87.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.86.0 lib/rubocop/cop/style/even_odd.rb
files.com-1.0.1 vendor/bundle/ruby/2.5.0/gems/rubocop-0.85.1/lib/rubocop/cop/style/even_odd.rb
rbhint-0.85.1.rc2 lib/rubocop/cop/style/even_odd.rb
rbhint-0.85.1.rc1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.85.1 lib/rubocop/cop/style/even_odd.rb
rbhint-0.8.5.rc1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.85.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.84.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.83.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.82.0 lib/rubocop/cop/style/even_odd.rb