Class: RuboCop::Cop::Layout::ClassStructure

Inherits:
Cop
  • Object
show all
Defined in:
lib/rubocop/cop/layout/class_structure.rb

Overview

Checks if the code style follows the ExpectedOrder configuration:

`Categories` allows us to map macro names into a category.

Consider an example of code style that covers the following order:

  • Constants

  • Associations (has_one, has_many)

  • Attributes (attr_accessor, attr_writer, attr_reader)

  • Initializer

  • Instance methods

  • Protected methods

  • Private methods

You can configure the following order:

“`yaml

Layout/ClassStructure:
  Categories:
    module_inclusion:
      - include
      - prepend
      - extend
  ExpectedOrder:
      - module_inclusion
      - constants
      - public_class_methods
      - initializer
      - public_methods
      - protected_methods
      - private_methods

“` Instead of putting all literals in the expected order, is also possible to group categories of macros.

“`yaml

Layout/ClassStructure:
  Categories:
    association:
      - has_many
      - has_one
    attribute:
      - attr_accessor
      - attr_reader
      - attr_writer

“`

Examples:

# bad
# Expect extend be before constant
class Person < ApplicationRecord
  has_many :orders
  ANSWER = 42

  extend SomeModule
  include AnotherModule
end

# good
class Person
  # extend and include go first
  extend SomeModule
  include AnotherModule

  # inner classes
  CustomError = Class.new(StandardError)

  # constants are next
  SOME_CONSTANT = 20

  # afterwards we have attribute macros
  attr_reader :name

  # followed by other macros (if any)
  validates :name

  # public class methods are next in line
  def self.some_method
  end

  # initialization goes between class methods and instance methods
  def initialize
  end

  # followed by other public instance methods
  def some_method
  end

  # protected and private methods are grouped near the end
  protected

  def some_protected_method
  end

  private

  def some_private_method
  end
end

See Also:

Constant Summary collapse

HUMANIZED_NODE_TYPE =
{
  casgn: :constants,
  defs: :class_methods,
  def: :public_methods
}.freeze
VISIBILITY_SCOPES =
%i[private protected public].freeze
MSG =
'`%<category>s` is supposed to appear before ' \
'`%<previous>s`.'.freeze

Constants included from Util

Util::ASGN_NODES, Util::CONDITIONAL_NODES, Util::EQUALS_ASGN_NODES, Util::LITERAL_REGEX, Util::LOGICAL_OPERATOR_NODES, Util::MODIFIER_NODES, Util::OPERATOR_METHODS, Util::SHORTHAND_ASGN_NODES

Instance Attribute Summary

Attributes inherited from Cop

#config, #corrections, #offenses, #processed_source

Instance Method Summary collapse

Methods inherited from Cop

#add_offense, all, autocorrect_incompatible_with, badge, #config_to_allow_offenses, #config_to_allow_offenses=, #cop_config, cop_name, #cop_name, #correct, department, #duplicate_location?, #excluded_file?, #find_location, #highlights, inherited, #initialize, #join_force?, lint?, match?, #message, #messages, non_rails, #parse, qualified_cop_name, #relevant_file?, #target_rails_version, #target_ruby_version

Methods included from NodePattern::Macros

#def_node_matcher, #def_node_search, #node_search, #node_search_all, #node_search_body, #node_search_first

Methods included from AST::Sexp

#s

Methods included from AutocorrectLogic

#autocorrect?, #autocorrect_enabled?, #autocorrect_requested?, #support_autocorrect?

Methods included from IgnoredNode

#ignore_node, #ignored_node?, #part_of_ignored_node?

Methods included from Util

begins_its_line?, comment_line?, double_quotes_required?, escape_string, first_part_of_call_chain, interpret_string_escapes, line_range, needs_escaping?, on_node, operator?, parentheses?, same_line?, to_string_literal, to_supported_styles, tokens

Methods included from PathUtil

absolute?, match_path?, pwd, relative_path, reset_pwd, smart_path

Constructor Details

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

Instance Method Details

#autocorrect(node) ⇒ Object

Autocorrect by swapping between two nodes autocorrecting them



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/rubocop/cop/layout/class_structure.rb', line 138

def autocorrect(node)
  node_classification = classify(node)
  previous = left_siblings_of(node).find do |sibling|
    classification = classify(sibling)
    !ignore?(classification) && node_classification != classification
  end

  current_range = source_range_with_comment(node)
  previous_range = source_range_with_comment(previous)

  lambda do |corrector|
    corrector.insert_before(previous_range, current_range.source)
    corrector.remove(current_range)
  end
end

#on_class(class_node) ⇒ Object

Validates code style on class declaration. Add offense when find a node out of expected order.



124
125
126
127
128
129
130
131
132
133
134
135
# File 'lib/rubocop/cop/layout/class_structure.rb', line 124

def on_class(class_node)
  previous = -1
  walk_over_nested_class_definition(class_node) do |node, category|
    index = expected_order.index(category)
    if index < previous
      message = format(MSG, category: category,
                            previous: expected_order[previous])
      add_offense(node, message: message)
    end
    previous = index
  end
end