123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::Next

Relationships & Source Files
Super Chains via Extension / Inclusion / Inheritance
Class Chain:
self, ::RuboCop::Cop::AutoCorrector, ::RuboCop::Cop::Base, ::RuboCop::ExcludeLimit, NodePattern::Macros, RuboCop::AST::Sexp
Instance Chain:
Inherits: RuboCop::Cop::Base
Defined in: lib/rubocop/cop/style/next.rb

Overview

Use next to skip iteration instead of a condition at the end.

Examples:

EnforcedStyle: skip_modifier_ifs (default)

# bad
[1, 2].each do |a|
  if a == 1
    puts a
  end
end

# good
[1, 2].each do |a|
  next unless a == 1
  puts a
end

# good
[1, 2].each do |a|
  puts a if a == 1
end

EnforcedStyle: always

# With {always} all conditions at the end of an iteration needs to be
# replaced by next - with {skip_modifier_ifs} the modifier if like
# this one are ignored: `[1, 2].each { |a| puts a if a == 1 }`

# bad
[1, 2].each do |a|
  puts a if a == 1
end

# bad
[1, 2].each do |a|
  if a == 1
    puts a
  end
end

# good
[1, 2].each do |a|
  next unless a == 1
  puts a
end

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

SYMBOL_TO_STRING_CACHE

::RuboCop::Cop::RangeHelp - Included

BYTE_ORDER_MARK, NOT_GIVEN

Class Attribute Summary

::RuboCop::Cop::AutoCorrector - Extended

::RuboCop::Cop::Base - Inherited

.gem_requirements, .lint?,
.support_autocorrect?

Returns if class supports autocorrect.

.support_multiple_source?

Override if your cop should be called repeatedly for multiple investigations Between calls to #on_new_investigation and on_investigation_end, the result of processed_source will remain constant.

Class Method Summary

::RuboCop::Cop::Base - Inherited

.autocorrect_incompatible_with

List of cops that should not try to autocorrect at the same time as this cop.

.badge

Naming.

.callbacks_needed, .cop_name, .department,
.documentation_url

Returns a url to view this cops documentation online.

.exclude_from_registry

Call for abstract Cop classes.

.inherited,
.joining_forces

Override and return the Force class(es) you need to join.

.match?

Returns true if the cop name or the cop namespace matches any of the given names.

.new,
.requires_gem

Register a version requirement for the given gem name.

.restrict_on_send

::RuboCop::ExcludeLimit - Extended

exclude_limit

Sets up a configuration option to have an exclude limit tracked.

transform

Instance Attribute Summary

Instance Method Summary

::RuboCop::Cop::RangeHelp - Included

#add_range, #column_offset_between,
#contents_range

A range containing only the contents of a literal with delimiters (e.g.

#directions,
#effective_column

Returns the column attribute of the range, except if the range is on the first line and there’s a byte order mark at the beginning of that line, in which case 1 is subtracted from the column value.

#final_pos, #move_pos, #move_pos_str, #range_between, #range_by_whole_lines, #range_with_comments, #range_with_comments_and_lines, #range_with_surrounding_comma, #range_with_surrounding_space, #source_range

::RuboCop::Cop::MinBodyLength - Included

::RuboCop::Cop::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::Base - Inherited

#add_global_offense

Adds an offense that has no particular location.

#add_offense

Adds an offense on the specified range (or node with an expression) Unless that offense is disabled for this range, a corrector will be yielded to provide the cop the opportunity to autocorrect the offense.

#begin_investigation

Called before any investigation.

#callbacks_needed,
#cop_config

Configuration Helpers.

#cop_name, #excluded_file?,
#external_dependency_checksum

This method should be overridden when a cop’s behavior depends on state that lives outside of these locations:

#inspect,
#message

Gets called if no message is specified when calling add_offense or add_global_offense Cops are discouraged to override this; instead pass your message directly.

#name

Alias for Base#cop_name.

#offenses,
#on_investigation_end

Called after all on_…​

#on_new_investigation

Called before all on_…​

#on_other_file

Called instead of all on_…​

#parse

There should be very limited reasons for a Cop to do it’s own parsing.

#parser_engine,
#ready

Called between investigations.

#relevant_file?, #target_rails_version, #target_ruby_version, #annotate, #apply_correction, #attempt_correction,
#callback_argument

Reserved for Cop::Cop.

#complete_investigation

Called to complete an investigation.

#correct, #current_corrector,
#current_offense_locations

Reserved for Commissioner:

#current_offenses, #currently_disabled_lines, #custom_severity, #default_severity, #disable_uncorrectable, #enabled_line?, #file_name_matches_any?, #find_message, #find_severity, #range_for_original, #range_from_node_or_range,
#reset_investigation

Actually private methods.

#use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

This class inherits a constructor from RuboCop::Cop::Base

Class Method Details

.autocorrect_incompatible_with

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 58

def self.autocorrect_incompatible_with
  [Style::SafeNavigation]
end

Instance Method Details

#actual_indent(lines, buffer) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 213

def actual_indent(lines, buffer)
  lines.map { |lineno| buffer.source_line(lineno) =~ /\S/ }.min
end

#allowed_modifier_if?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 112

def allowed_modifier_if?(node)
  if node.modifier_form?
    style == :skip_modifier_ifs
  else
    !min_body_length?(node)
  end
end

#autocorrect_block(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 155

def autocorrect_block(corrector, node)
  next_code = "next #{node.inverse_keyword} #{node.condition.source}"

  corrector.insert_before(node, next_code)

  corrector.remove(cond_range(node, node.condition))
  corrector.remove(end_range(node))

  lines = reindentable_lines(node)

  return if lines.empty?

  reindent(lines, node.condition, corrector)
end

#autocorrect_modifier(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 145

def autocorrect_modifier(corrector, node)
  body = node.if_branch || node.else_branch

  replacement =
    "next #{node.inverse_keyword} #{node.condition.source}\n" \
    "#{' ' * node.source_range.column}#{body.source}"

  corrector.replace(node, replacement)
end

#check(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 84

def check(node)
  return unless node.body && ends_with_condition?(node.body)

  offending_node = offense_node(node.body)

  add_offense(offense_location(offending_node)) do |corrector|
    if offending_node.modifier_form?
      autocorrect_modifier(corrector, offending_node)
    else
      autocorrect_block(corrector, offending_node)
    end
  end
end

#cond_range(node, cond) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 170

def cond_range(node, cond)
  end_pos = if node.loc.begin
              node.loc.begin.end_pos # after "then"
            else
              cond.source_range.end_pos
            end

  range_between(node.source_range.begin_pos, end_pos)
end

#end_followed_by_whitespace_only?(source_buffer, end_pos) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 189

def end_followed_by_whitespace_only?(source_buffer, end_pos)
  /\A\s*$/.match?(source_buffer.source[end_pos..])
end

#end_range(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 180

def end_range(node)
  source_buffer = node.source_range.source_buffer
  end_pos = node.loc.end.end_pos
  begin_pos = node.loc.end.begin_pos - node.loc.end.column
  begin_pos -= 1 if end_followed_by_whitespace_only?(source_buffer, end_pos)

  range_between(begin_pos, end_pos)
end

#ends_with_condition?(body) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 98

def ends_with_condition?(body)
  return true if simple_if_without_break?(body)

  body.begin_type? && simple_if_without_break?(body.children.last)
end

#exit_body_type?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 128

def exit_body_type?(node)
  return false unless node.if_branch

  EXIT_TYPES.include?(node.if_branch.type)
end

#heredoc_lines(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 217

def heredoc_lines(node)
  node.each_node(:dstr)
      .select(&:heredoc?)
      .map { |n| n.loc.heredoc_body }
      .flat_map { |b| (b.line...b.last_line).to_a }
end

#if_else_children?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 120

def if_else_children?(node)
  node.each_child_node(:if).any?(&:else?)
end

#if_without_else?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 124

def if_without_else?(node)
  node&.if_type? && !node.ternary? && !node.else?
end

#offense_location(offense_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 140

def offense_location(offense_node)
  offense_begin_pos = offense_node.source_range.begin
  offense_begin_pos.join(offense_node.condition.source_range)
end

#offense_node(body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 134

def offense_node(body)
  *_, condition = *body

  condition&.if_type? ? condition : body
end

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 68

def on_block(node)
  return unless node.send_node.call_type? && node.send_node.enumerator_method?

  check(node)
end

#on_for(node)

Alias for #on_while.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 80

alias on_for on_while

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 62

def on_new_investigation
  # When correcting nested offenses, we need to keep track of how much
  # we have adjusted the indentation of each line
  @reindented_lines = Hash.new(0)
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 74

alias on_numblock on_block

#on_until(node)

Alias for #on_while.

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 79

alias on_until on_while

#on_while(node) Also known as: #on_until, #on_for

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 76

def on_while(node)
  check(node)
end

#reindent(lines, node, corrector) (private)

Adjust indentation of lines to match node

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 204

def reindent(lines, node, corrector)
  range  = node.source_range
  buffer = range.source_buffer

  target_indent = range.source_line =~ /\S/
  delta = actual_indent(lines, buffer) - target_indent
  lines.each { |lineno| reindent_line(corrector, lineno, delta, buffer) }
end

#reindent_line(corrector, lineno, delta, buffer) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 224

def reindent_line(corrector, lineno, delta, buffer)
  adjustment = delta + @reindented_lines[lineno]
  @reindented_lines[lineno] = adjustment

  corrector.remove_leading(buffer.line_range(lineno), adjustment) if adjustment.positive?
end

#reindentable_lines(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 193

def reindentable_lines(node)
  buffer = node.source_range.source_buffer

  # end_range starts with the final newline of the if body
  lines = (node.source_range.line + 1)...node.loc.end.line
  lines = lines.to_a - heredoc_lines(node)
  # Skip blank lines
  lines.reject { |lineno| /\A\s*\z/.match?(buffer.source_line(lineno)) }
end

#simple_if_without_break?(node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/next.rb', line 104

def simple_if_without_break?(node)
  return false unless if_without_else?(node)
  return false if if_else_children?(node)
  return false if allowed_modifier_if?(node)

  !exit_body_type?(node)
end