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:

  • Module inclusion (include, prepend, extend)

  • Constants

  • Associations (has_one, has_many)

  • Public attribute macros (attr_accessor, attr_writer, attr_reader)

  • Other macros (validates, validate)

  • Public class methods

  • Initializer

  • Public instance methods

  • Protected attribute macros (attr_accessor, attr_writer, attr_reader)

  • Protected instance methods

  • Private attribute macros (attr_accessor, attr_writer, attr_reader)

  • Private instance methods

You can configure the following order:

“‘yaml

Layout/ClassStructure:
  ExpectedOrder:
    - module_inclusion
    - constants
    - association
    - public_attribute_macros
    - public_delegate
    - macros
    - public_class_methods
    - initializer
    - public_methods
    - protected_attribute_macros
    - protected_methods
    - private_attribute_macros
    - private_delegate
    - private_methods

“‘

Instead of putting all literals in the expected order, is also possible to group categories of macros. Visibility levels are handled automatically.

“‘yaml

Layout/ClassStructure:
  Categories:
    association:
      - has_many
      - has_one
    attribute_macros:
      - attr_accessor
      - attr_reader
      - attr_writer
    macros:
      - validates
      - validate
    module_inclusion:
      - include
      - prepend
      - extend

“‘

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 public attribute macros
  attr_reader :name

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

  # then we have public delegate macros
  delegate :to_s, to: :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 attribute macros and methods go next
  protected

  attr_reader :protected_name

  def some_protected_method
  end

  # private attribute macros, delegate macros and methods
  # are grouped near the end
  private

  attr_reader :private_name

  delegate :some_private_delegate, to: :name

  def some_private_method
  end
end

See Also:

Constant Summary collapse

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

Constants included from Util

Util::LITERAL_REGEX

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 AST::Sexp

#s

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 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, parentheses?, same_line?, to_string_literal, to_supported_styles, tokens, trim_string_interporation_escape_character

Methods included from PathUtil

absolute?, chdir, hidden_dir?, hidden_file_in_not_hidden_dir?, 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



165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/rubocop/cop/layout/class_structure.rb', line 165

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.



151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/rubocop/cop/layout/class_structure.rb', line 151

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