123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Layout::ExtraSpacing

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/layout/extra_spacing.rb

Overview

Checks for extra/unnecessary whitespace.

Examples:

# good if AllowForAlignment is true
name      = "RuboCop"
# Some comment and an empty line

website  += "/rubocop/rubocop" unless cond
puts        "rubocop"          if     debug

# bad for any configuration
set_app("RuboCop")
website  = "https://github.com/rubocop/rubocop"

# good only if AllowBeforeTrailingComments is true
object.method(arg)  # this is a comment

# good even if AllowBeforeTrailingComments is false or not set
object.method(arg) # this is a comment

# good with either AllowBeforeTrailingComments or AllowForAlignment
object.method(arg)         # this is a comment
another_object.method(arg) # this is another comment
some_object.method(arg)    # this is some comment

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::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.

.builtin?

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

Cops (other than builtin) are encouraged to implement this.

.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::PrecedingFollowingAlignment - 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, #use_corrector

::RuboCop::Cop::AutocorrectLogic - Included

::RuboCop::Cop::IgnoredNode - Included

Constructor Details

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

Instance Attribute Details

#allow_for_trailing_comments?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 179

def allow_for_trailing_comments?
  cop_config['AllowBeforeTrailingComments']
end

#force_equal_sign_alignment?Boolean (readonly, private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 133

def force_equal_sign_alignment?
  cop_config['ForceEqualSignAlignment']
end

Instance Method Details

#align_column(asgn_token) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 170

def align_column(asgn_token)
  # if we removed unneeded spaces from the beginning of this =,
  # what column would it end from?
  line    = processed_source.lines[asgn_token.line - 1]
  leading = line[0...asgn_token.column]
  spaces  = leading.size - (leading =~ / *\Z/)
  asgn_token.pos.last_column - spaces + 1
end

#align_equal_sign(corrector, token, align_to) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 147

def align_equal_sign(corrector, token, align_to)
  return unless @corrected.add?(token)

  diff = align_to - token.pos.last_column

  if diff.positive?
    corrector.insert_before(token.pos, ' ' * diff)
  elsif diff.negative?
    corrector.remove_preceding(token.pos, -diff)
  end
end

#align_equal_signs(range, corrector) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 137

def align_equal_signs(range, corrector)
  lines  = all_relevant_assignment_lines(range.line)
  tokens = assignment_tokens.select { |t| lines.include?(t.line) }

  columns  = tokens.map { |t| align_column(t) }
  align_to = columns.max

  tokens.each { |token| align_equal_sign(corrector, token, align_to) }
end

#aligned_locations(locs) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 52

def aligned_locations(locs)
  return [] if locs.empty?

  aligned = Set.new
  locs.each_cons(2) do |loc1, loc2|
    aligned << loc1.line << loc2.line if loc1.column == loc2.column
  end
  aligned
end

#aligned_tok?(token) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 103

def aligned_tok?(token)
  if token.comment?
    @aligned_comments.include?(token.line)
  else
    aligned_with_something?(token.pos)
  end
end

#all_relevant_assignment_lines(line_number) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 159

def all_relevant_assignment_lines(line_number)
  last_line_number = processed_source.lines.size

  (
    relevant_assignment_lines(line_number.downto(1)) +
    relevant_assignment_lines(line_number.upto(last_line_number))
  )
    .uniq
    .sort
end

#check_assignment(token) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 72

def check_assignment(token)
  return unless aligned_with_preceding_assignment(token) == :no

  message = format(MSG_UNALIGNED_ASGN, location: 'preceding')
  add_offense(token.pos, message: message) do |corrector|
    align_equal_signs(token.pos, corrector)
  end
end

#check_other(token1, token2, ast) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 81

def check_other(token1, token2, ast)
  return false if allow_for_trailing_comments? && token2.text.start_with?('#')

  extra_space_range(token1, token2) do |range|
    next if ignored_range?(ast, range.begin_pos)

    add_offense(range, message: MSG_UNNECESSARY) { |corrector| corrector.remove(range) }
  end
end

#check_tokens(ast, token1, token2) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 62

def check_tokens(ast, token1, token2)
  return if token2.type == :tNL

  if force_equal_sign_alignment? && assignment_tokens.include?(token2)
    check_assignment(token2)
  else
    check_other(token1, token2, ast)
  end
end

#extra_space_range(token1, token2) {|range_between(start_pos, end_pos)| ... } (private)

Yields:

  • (range_between(start_pos, end_pos))
[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 91

def extra_space_range(token1, token2)
  return if token1.line != token2.line

  start_pos = token1.end_pos
  end_pos = token2.begin_pos - 1
  return if end_pos <= start_pos

  return if allow_for_alignment? && aligned_tok?(token2)

  yield range_between(start_pos, end_pos)
end

#ignored_range?(ast, start_pos) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 111

def ignored_range?(ast, start_pos)
  ignored_ranges(ast).any? { |r| r.include?(start_pos) }
end

#ignored_ranges(ast) (private)

Returns an array of ranges that should not be reported. It’s the extra spaces between the keys and values in a multiline hash, since those are handled by the Layout/HashAlignment cop.

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 118

def ignored_ranges(ast)
  return [] unless ast

  @ignored_ranges ||= begin
    ranges = []
    on_node(:pair, ast) do |pair|
      next if pair.parent.single_line?

      key, value = *pair
      ranges << (key.source_range.end_pos...value.source_range.begin_pos)
    end
    ranges
  end
end

#on_new_investigation

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/extra_spacing.rb', line 39

def on_new_investigation
  return if processed_source.blank?

  @aligned_comments = aligned_locations(processed_source.comments.map(&:loc))
  @corrected = Set.new if force_equal_sign_alignment?

  processed_source.tokens.each_cons(2) do |token1, token2|
    check_tokens(processed_source.ast, token1, token2)
  end
end