123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Layout::BlockAlignment

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/block_alignment.rb

Overview

Checks whether the end keywords are aligned properly for do end blocks.

Three modes are supported through the EnforcedStyleAlignWith configuration parameter:

start_of_block : the end shall be aligned with the start of the line where the do appeared.

start_of_line : the end shall be aligned with the start of the line where the expression started.

either (which is the default) : the end is allowed to be in either location. The autofixer will default to start_of_line.

Examples:

EnforcedStyleAlignWith: either (default)

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
end

EnforcedStyleAlignWith: start_of_block

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
  end

EnforcedStyleAlignWith: start_of_line

# bad

foo.bar
  .each do
    baz
      end

# good

foo.bar
  .each do
    baz
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 an 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::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

Instance Method Details

#add_space_before(corrector, loc, delta) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 228

def add_space_before(corrector, loc, delta)
  corrector.insert_before(loc, ' ' * delta)
end

#alt_start_msg(start_loc, source_line_column) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 205

def alt_start_msg(start_loc, source_line_column)
  if style != :either ||
     (start_loc.line == source_line_column[:line] &&
         start_loc.column == source_line_column[:column])
    ''
  else
    " or #{format_source_line_column(source_line_column)}"
  end
end

#autocorrect(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 155

def autocorrect(corrector, node)
  ancestor_node = start_for_block_node(node)
  start_col = compute_start_col(ancestor_node, node)
  loc_end = node.loc.end
  delta = start_col - loc_end.column

  if delta.positive?
    add_space_before(corrector, loc_end, delta)
  elsif delta.negative?
    remove_space_before(corrector, loc_end.begin_pos, -delta)
  end
end

#block_end_align_target(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 105

def block_end_align_target(node)
  lineage = [node, *node.ancestors]

  lineage.each_cons(2) do |current, parent|
    return current if end_align_target?(current, parent)
  end

  lineage.last
end

#block_end_align_target?(node, child)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 74

def_node_matcher :block_end_align_target?, <<~PATTERN
  {assignment?
   splat
   and
   or
   (send _ :<<  ...)
   (send equal?(%1) !:[] ...)}
PATTERN

#check_block_alignment(start_node, block_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 123

def check_block_alignment(start_node, block_node)
  end_loc = block_node.loc.end
  return unless begins_its_line?(end_loc)

  start_loc = start_node.source_range
  return unless start_loc.column != end_loc.column || style == :start_of_block

  do_source_line_column = compute_do_source_line_column(block_node, end_loc)
  return unless do_source_line_column

  register_offense(block_node, start_loc, end_loc, do_source_line_column)
end

#compute_do_source_line_column(node, end_loc) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 178

def compute_do_source_line_column(node, end_loc)
  do_loc = node.loc.begin # Actually it's either do or {.

  # We've found that "end" is not aligned with the start node (which
  # can be a block, a variable assignment, etc). But we also allow
  # the "end" to be aligned with the start of the line where the "do"
  # is, which is a style some people use in multi-line chains of
  # blocks.
  match = /\S.*/.match(do_loc.source_line)
  indentation_of_do_line = match.begin(0)
  return unless end_loc.column != indentation_of_do_line || style == :start_of_line

  {
    source: match[0],
    line: do_loc.line,
    column: indentation_of_do_line
  }
end

#compute_start_col(ancestor_node, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 220

def compute_start_col(ancestor_node, node)
  if style == :start_of_block
    do_loc = node.loc.begin
    return do_loc.source_line =~ /\S/
  end
  (ancestor_node || node).source_range.column
end

#disqualified_parent?(parent, node) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 119

def disqualified_parent?(parent, node)
  parent&.loc && parent.first_line != node.first_line && !parent.masgn_type?
end

#end_align_target?(node, parent) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 115

def end_align_target?(node, parent)
  disqualified_parent?(parent, node) || !block_end_align_target?(parent, node)
end

#format_message(start_loc, end_loc, do_source_line_column, error_source_line_column) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 168

def format_message(start_loc, end_loc, do_source_line_column,
                   error_source_line_column)
  format(
    MSG,
    current: format_source_line_column(loc_to_source_line_column(end_loc)),
    prefer: format_source_line_column(error_source_line_column),
    alt_prefer: alt_start_msg(start_loc, do_source_line_column)
  )
end

#format_source_line_column(source_line_column) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 215

def format_source_line_column(source_line_column)
  "`#{source_line_column[:source]}` at #{source_line_column[:line]}, " \
    "#{source_line_column[:column]}"
end

#loc_to_source_line_column(loc) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 197

def loc_to_source_line_column(loc)
  {
    source: loc.source.lines.to_a.first.chomp,
    line: loc.line,
    column: loc.column
  }
end

#on_block(node) Also known as: #on_numblock

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 83

def on_block(node)
  check_block_alignment(start_for_block_node(node), node)
end

#on_numblock(node)

Alias for #on_block.

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 87

alias on_numblock on_block

#register_offense(block_node, start_loc, end_loc, do_source_line_column) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 136

def register_offense(block_node,
                     start_loc,
                     end_loc,
                     do_source_line_column)

  error_source_line_column = if style == :start_of_block
                               do_source_line_column
                             else
                               loc_to_source_line_column(start_loc)
                             end

  message = format_message(start_loc, end_loc, do_source_line_column,
                           error_source_line_column)

  add_offense(end_loc, message: message) do |corrector|
    autocorrect(corrector, block_node)
  end
end

#remove_space_before(corrector, end_pos, delta) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 232

def remove_space_before(corrector, end_pos, delta)
  range = range_between(end_pos - delta, end_pos)

  corrector.remove(range)
end

#start_for_block_node(block_node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 95

def start_for_block_node(block_node)
  # Which node should we align the 'end' with?
  result = block_end_align_target(block_node)

  # In offense message, we want to show the assignment LHS rather than
  # the entire assignment
  result, = *result while result.op_asgn_type? || result.masgn_type?
  result
end

#style_parameter_name

[ GitHub ]

  
# File 'lib/rubocop/cop/layout/block_alignment.rb', line 89

def style_parameter_name
  'EnforcedStyleAlignWith'
end