class RuboCop::Cop::Lint::ShadowingOuterLocalVariable
end
end
do_something(bar)
2.times do |bar|
foo = 1
def some_method
# good
@example
end
end
do_something(foo)
2.times do |foo| # shadowing outer ‘foo`
foo = 1
def some_method
# bad
@example
—-
end
Ractor.new(worker_id, pipe) do |worker_id, pipe|
worker_id, pipe = env
—-
[source,ruby]
eg. following style is encouraged:
because `Ractor` should not access outer variables.
NOTE: Shadowing of variables in block passed to `Ractor.new` is allowed
“shadowing outer local variable - foo”.
given by `ruby -cw` prior to Ruby 2.6:
in block arguments or block-local variables. This mirrors the warning
Checks for the use of local variable names from an outer scope
def self.joining_forces
def self.joining_forces VariableForce end
def before_declaring_variable(variable, variable_table)
def before_declaring_variable(variable, variable_table) return if variable.should_be_unused? return if ractor_block?(variable.scope.node) outer_local_variable = variable_table.find_variable(variable.name) return unless outer_local_variable return if same_conditions_node_different_branch?(variable, outer_local_variable) message = format(MSG, variable: variable.name) add_offense(variable.declaration_node, message: message) end
def find_conditional_node_from_ascendant(node)
def find_conditional_node_from_ascendant(node) return unless (parent = node.parent) return parent if parent.conditional? find_conditional_node_from_ascendant(parent) end
def same_conditions_node_different_branch?(variable, outer_local_variable)
def same_conditions_node_different_branch?(variable, outer_local_variable) variable_node = variable_node(variable) return false unless variable_node.conditional? outer_local_variable_node = find_conditional_node_from_ascendant(outer_local_variable.declaration_node) return true unless outer_local_variable_node return false unless outer_local_variable_node.conditional? return true if variable_node == outer_local_variable_node outer_local_variable_node.if_type? && variable_node == outer_local_variable_node.else_branch end
def variable_node(variable)
def variable_node(variable) parent_node = variable.scope.node.parent if parent_node.when_type? parent_node.parent else parent_node end end