class RuboCop::Cop::Lint::AssignmentInCondition
This cop checks for assignments in the conditions of if/while/until.
@example
# bad if some_var = true do_something end
@example
# good if some_var == true do_something end
Constants
- ASGN_TYPES
- MSG_WITHOUT_SAFE_ASSIGNMENT_ALLOWED
- MSG_WITH_SAFE_ASSIGNMENT_ALLOWED
Public Instance Methods
on_if(node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 35 def on_if(node) check(node) end
on_until(node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 43 def on_until(node) check(node) end
on_while(node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 39 def on_while(node) check(node) end
Private Instance Methods
allowed_construct?(asgn_node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 68 def allowed_construct?(asgn_node) asgn_node.begin_type? || conditional_assignment?(asgn_node) end
check(node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 57 def check(node) return if node.condition.block_type? traverse_node(node.condition, ASGN_TYPES) do |asgn_node| next :skip_children if skip_children?(asgn_node) next if allowed_construct?(asgn_node) add_offense(asgn_node, location: :operator) end end
conditional_assignment?(asgn_node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 72 def conditional_assignment?(asgn_node) !asgn_node.loc.operator end
message(_node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 49 def message(_node) if safe_assignment_allowed? MSG_WITH_SAFE_ASSIGNMENT_ALLOWED else MSG_WITHOUT_SAFE_ASSIGNMENT_ALLOWED end end
skip_children?(asgn_node)
click to toggle source
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 76 def skip_children?(asgn_node) (asgn_node.send_type? && asgn_node.method_name !~ /=\z/) || empty_condition?(asgn_node) || (safe_assignment_allowed? && safe_assignment?(asgn_node)) end
traverse_node(node, types) { |node| ... }
click to toggle source
each_node/visit_descendants_with_types with :skip_children
# File lib/rubocop/cop/lint/assignment_in_condition.rb, line 83 def traverse_node(node, types, &block) result = yield node if types.include?(node.type) return if result == :skip_children node.each_child_node { |child| traverse_node(child, types, &block) } end