Sha256: f6a6abd0df8e15cd8a51afe5b4d447ce2607808e24595530a16bffb4d9311beb

Contents?: true

Size: 1.76 KB

Versions: 4

Compression:

Stored size: 1.76 KB

Contents

# encoding: utf-8

module RuboCop
  module Cop
    module Style
      # This cop checks for places where Fixnum#even? or Fixnum#odd?
      # should have been used.
      #
      # @example
      #
      #   # bad
      #   if x % 2 == 0
      #
      #   # good
      #   if x.even?
      class EvenOdd < Cop
        MSG = 'Replace with `Fixnum#%s?`.'

        ZERO = s(:int, 0)
        ONE = s(:int, 1)
        TWO = s(:int, 2)

        def on_send(node)
          offense = offense_type(node)
          add_offense(node, :expression, format(MSG, offense)) if offense
        end

        def autocorrect(node)
          @corrections << lambda do |corrector|
            correction = "#{base_number(node)}.#{offense_type(node)}?"
            corrector.replace(node.loc.expression, correction)
          end
        end

        private

        def base_number(node)
          receiver, = *node
          node = expression(receiver)
          node.children[0].loc.expression.source
        end

        def offense_type(node)
          receiver, method, args = *node

          return unless [:==, :!=].include?(method)
          return unless div_by_2?(receiver)

          if args == ZERO
            method == :== ? :even : :odd
          elsif args == ONE
            method == :== ? :odd : :even
          end
        end

        def div_by_2?(node)
          node = expression(node)

          _receiver, method, args = *node

          method == :% && args == TWO
        end

        def expression(node)
          return unless node

          # check for scenarios like (x % 2) == 0
          if node.type == :begin && node.children.size == 1
            node = node.children.first
          end

          return unless node.type == :send
          node
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
rubocop-0.30.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.30.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.29.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.29.0 lib/rubocop/cop/style/even_odd.rb