Sha256: b8b48c1c3f7bd3e23b4fae4a8b698c4f35d6f0933d7ad20c605f74aa1449349e

Contents?: true

Size: 1.32 KB

Versions: 1

Compression:

Stored size: 1.32 KB

Contents

# encoding: utf-8

module Rubocop
  module Cop
    module Lint
      # This cop checks for assignments in the conditions of
      # if/while/until.
      class AssignmentInCondition < Cop
        ASGN_NODES = [:lvasgn, :ivasgn, :cvasgn, :gvasgn, :casgn]
        MSG = 'Assignment in condition - you probably meant to use ==.'

        def on_if(node)
          check(node)
        end

        def on_while(node)
          check(node)
        end

        def on_until(node)
          check(node)
        end

        private

        def check(node)
          condition, = *node

          on_node([:begin, *ASGN_NODES], condition) do |asgn_node|
            # skip safe assignment nodes if safe assignment is allowed
            return if safe_assignment_allowed? && safe_assignment?(asgn_node)

            # assignment nodes from shorthand ops like ||= don't have operator
            if asgn_node.type != :begin && asgn_node.loc.operator
              add_offence(:warning, asgn_node.loc.operator, MSG)
            end
          end
        end

        def safe_assignment?(node)
          node.type == :begin && node.children.size == 1 &&
            ASGN_NODES.include?(node.children[0].type)
        end

        def safe_assignment_allowed?
          AssignmentInCondition.config['AllowSafeAssignment']
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rubocop-0.10.0 lib/rubocop/cop/lint/assignment_in_condition.rb