Enabling Layout/ClassStructure
Layout/ClassStructure
checks if the code style follows the ExpectedOrder configuration:
- 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
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