Sha256: c2c776934bd74604f214f5ebc1ea3e819d73f08ed667de8efb695814c6ac0380

Contents?: true

Size: 1.36 KB

Versions: 11

Compression:

Stored size: 1.36 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_EVEN = 'Replace with `Fixnum#even?`.'
        MSG_ODD = 'Replace with `Fixnum#odd?`.'

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

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

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

          if args == ZERO
            add_offense(node,
                        :expression,
                        method == :== ? MSG_EVEN : MSG_ODD)
          elsif args == ONE
            add_offense(node,
                        :expression,
                        method == :== ? MSG_ODD : MSG_EVEN)
          end
        end

        private

        def div_by_2?(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

          _receiver, method, args = *node

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

Version data entries

11 entries across 11 versions & 2 rubygems

Version Path
rubyjobbuilderdsl-0.0.2 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/even_odd.rb
rubyjobbuilderdsl-0.0.1 vendor/bundle/ruby/2.1.0/gems/rubocop-0.26.0/lib/rubocop/cop/style/even_odd.rb
rubocop-0.28.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.27.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.27.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.26.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.26.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.25.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.24.1 lib/rubocop/cop/style/even_odd.rb
rubocop-0.24.0 lib/rubocop/cop/style/even_odd.rb
rubocop-0.23.0 lib/rubocop/cop/style/even_odd.rb