lib/rubocop/cop/style/infinite_loop.rb in rubocop-0.89.0 vs lib/rubocop/cop/style/infinite_loop.rb in rubocop-0.89.1

- old
+ new

@@ -13,17 +13,19 @@ # # # good # loop do # work # end - class InfiniteLoop < Cop + class InfiniteLoop < Base + extend AutoCorrector + LEADING_SPACE = /\A(\s*)/.freeze MSG = 'Use `Kernel#loop` for infinite loops.' - def join_force?(force_class) - force_class == VariableForce + def self.joining_forces + VariableForce end def after_leaving_scope(scope, _variable_table) @variables ||= [] @variables.concat(scope.variables.values) @@ -38,20 +40,10 @@ end alias on_while_post on_while alias on_until_post on_until - def autocorrect(node) - if node.while_post_type? || node.until_post_type? - replace_begin_end_with_modifier(node) - elsif node.modifier_form? - replace_source(node.source_range, modifier_replacement(node)) - else - replace_source(non_modifier_range(node), 'loop do') - end - end - private def while_or_until(node) range = node.source_range # Not every `while true` and `until false` can be turned into a @@ -64,13 +56,25 @@ assigned_inside_loop?(var, range) && !assigned_before_loop?(var, range) && referenced_after_loop?(var, range) end - add_offense(node, location: :keyword) + add_offense(node.loc.keyword) do |corrector| + autocorrect(corrector, node) + end end + def autocorrect(corrector, node) + if node.while_post_type? || node.until_post_type? + replace_begin_end_with_modifier(corrector, node) + elsif node.modifier_form? + replace_source(corrector, node.source_range, modifier_replacement(node)) + else + replace_source(corrector, non_modifier_range(node), 'loop do') + end + end + def assigned_inside_loop?(var, range) var.assignments.any? { |a| range.contains?(a.node.source_range) } end def assigned_before_loop?(var, range) @@ -81,20 +85,16 @@ def referenced_after_loop?(var, range) e = range.end_pos var.references.any? { |r| r.node.source_range.begin_pos > e } end - def replace_begin_end_with_modifier(node) - lambda do |corrector| - corrector.replace(node.body.loc.begin, 'loop do') - corrector.remove(node.body.loc.end.end.join(node.source_range.end)) - end + def replace_begin_end_with_modifier(corrector, node) + corrector.replace(node.body.loc.begin, 'loop do') + corrector.remove(node.body.loc.end.end.join(node.source_range.end)) end - def replace_source(range, replacement) - lambda do |corrector| - corrector.replace(range, replacement) - end + def replace_source(corrector, range, replacement) + corrector.replace(range, replacement) end def modifier_replacement(node) body = node.body if node.single_line?