123456789_123456789_123456789_123456789_123456789_

Class: RuboCop::Cop::Style::ClassAndModuleChildren

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

Overview

Checks the style of children definitions at classes and modules. Basically there are two different styles:

The compact style is only forced for classes/modules with one child.

Examples:

EnforcedStyle: nested (default)

# good
# have each child on its own line
class Foo
  class Bar
  end
end

EnforcedStyle: compact

# good
# combine definitions as much as possible
class Foo::Bar
end

Cop Safety Information:

  • Autocorrection is unsafe.

    Moving from compact to nested children requires knowledge of whether the outer parent is a module or a class. Moving from nested to compact requires verification that the outer parent is defined elsewhere. RuboCop does not have the knowledge to perform either operation safely and thus requires manual oversight.

Constant Summary

::RuboCop::Cop::Base - Inherited

EMPTY_OFFENSES, RESTRICT_ON_SEND

::RuboCop::Cop::Alignment - Included

SPACE

::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::ConfigurableEnforcedStyle - Included

::RuboCop::Cop::Alignment - 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_gem_version

Returns a gems locked versions (i.e.

#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_trailing_end(corrector, node, padding) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 89

def add_trailing_end(corrector, node, padding)
  replacement = "#{padding}end\n#{leading_spaces(node)}end"
  corrector.replace(node.loc.end, replacement)
end

#autocorrect(corrector, node) (private)

[ GitHub ]

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

def autocorrect(corrector, node)
  return if node.class_type? && node.parent_class && style != :nested

  nest_or_compact(corrector, node)
end

#check_compact_style(node, body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 159

def check_compact_style(node, body)
  parent = node.parent
  return if parent&.class_type? || parent&.module_type?

  return unless needs_compacting?(body)

  add_offense(node.loc.name, message: COMPACT_MSG) do |corrector|
    autocorrect(corrector, node)
  end
end

#check_nested_style(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 151

def check_nested_style(node)
  return unless compact_node_name?(node)

  add_offense(node.loc.name, message: NESTED_MSG) do |corrector|
    autocorrect(corrector, node)
  end
end

#check_style(node, body) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 141

def check_style(node, body)
  return if node.identifier.namespace&.cbase_type?

  if style == :nested
    check_nested_style(node)
  else
    check_compact_style(node, body)
  end
end

#compact_definition(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 94

def compact_definition(corrector, node)
  compact_node(corrector, node)
  remove_end(corrector, node.body)
  unindent(corrector, node)
end

#compact_identifier_name(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 115

def compact_identifier_name(node)
  "#{node.identifier.const_name}::" \
    "#{node.body.children.first.const_name}"
end

#compact_node(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 100

def compact_node(corrector, node)
  range = range_between(node.loc.keyword.begin_pos, node.body.loc.name.end_pos)
  corrector.replace(range, compact_replacement(node))
end

#compact_node_name?(node) ⇒ Boolean (private)

[ GitHub ]

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

def compact_node_name?(node)
  node.identifier.source.include?('::')
end

#compact_replacement(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 105

def compact_replacement(node)
  replacement = "#{node.body.type} #{compact_identifier_name(node)}"

  body_comments = processed_source.ast_with_comments[node.body]
  unless body_comments.empty?
    replacement = body_comments.map(&:text).push(replacement).join("\n")
  end
  replacement
end

#leading_spaces(node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 137

def leading_spaces(node)
  node.source_range.source_line[/\A\s*/]
end

#needs_compacting?(body) ⇒ Boolean (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 176

def needs_compacting?(body)
  body && %i[module class].include?(body.type)
end

#nest_definition(corrector, node) (private)

[ GitHub ]

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

def nest_definition(corrector, node)
  padding = indentation(node) + leading_spaces(node)
  padding_for_trailing_end = padding.sub(' ' * node.loc.end.column, '')

  replace_namespace_keyword(corrector, node)
  split_on_double_colon(corrector, node, padding)
  add_trailing_end(corrector, node, padding_for_trailing_end)
end

#nest_or_compact(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 54

def nest_or_compact(corrector, node)
  if style == :nested
    nest_definition(corrector, node)
  else
    compact_definition(corrector, node)
  end
end

#on_class(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 42

def on_class(node)
  return if node.parent_class && style != :nested

  check_style(node, node.body)
end

#on_module(node)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 48

def on_module(node)
  check_style(node, node.body)
end

#remove_end(corrector, body) (private)

[ GitHub ]

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

def remove_end(corrector, body)
  remove_begin_pos = body.loc.end.begin_pos - leading_spaces(body).size
  adjustment = processed_source.raw_source[remove_begin_pos] == ';' ? 0 : 1
  range = range_between(remove_begin_pos, body.loc.end.end_pos + adjustment)

  corrector.remove(range)
end

#replace_namespace_keyword(corrector, node) (private)

[ GitHub ]

  
# File 'lib/rubocop/cop/style/class_and_module_children.rb', line 71

def replace_namespace_keyword(corrector, node)
  class_definition = node.left_sibling&.each_node(:class)&.find do |class_node|
    class_node.identifier == node.identifier.namespace
  end
  namespace_keyword = class_definition ? 'class' : 'module'

  corrector.replace(node.loc.keyword, namespace_keyword)
end

#split_on_double_colon(corrector, node, padding) (private)

[ GitHub ]

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

def split_on_double_colon(corrector, node, padding)
  children_definition = node.children.first
  range = range_between(children_definition.loc.double_colon.begin_pos,
                        children_definition.loc.double_colon.end_pos)
  replacement = "\n#{padding}#{node.loc.keyword.source} "

  corrector.replace(range, replacement)
end

#unindent(corrector, node) (private)

[ GitHub ]

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

def unindent(corrector, node)
  return if node.body.children.last.nil?

  column_delta = configured_indentation_width - leading_spaces(node.body.children.last).size
  return if column_delta.zero?

  AlignmentCorrector.correct(corrector, processed_source, node, column_delta)
end