Module: RuboCop::Cop::Asjer::RailsClassOrderDefaults

Defined in:
lib/rubocop/cop/asjer/rails_class_order.rb

Overview

Enforces consistent ordering of declarative methods in Rails models.

Methods are grouped into seven categories following Rails Style Guide: scopes, attributes, enums, associations, validations, callbacks, and others. Within each category, methods are sorted by their position in the configured list. Groups are separated by blank lines.

The order is: scopes, attributes, enums, associations, validations, callbacks, then others.

Default method lists for RailsClassOrder cop

Examples:

# bad
class User < ApplicationRecord
  belongs_to :plan
  validate :validate_name
  after_create :after_create_1
  has_many :messages
  scope :active, -> { where(active: true) }
  attr_readonly :email
  enum :status, [:pending, :active]
  after_create :after_create_2
  belongs_to :role
  before_create :set_name
end

# good
class User < ApplicationRecord
  scope :active, -> { where(active: true) }

  attr_readonly :email

  enum :status, [:pending, :active]

  belongs_to :plan
  belongs_to :role
  has_many :messages

  validate :validate_name

  before_create :set_name
  after_create :after_create_1
  after_create :after_create_2
end

Constant Summary collapse

SCOPES =
%w[default_scope scope].freeze
ATTRIBUTES =
%w[
  attr_accessor attr_reader attr_writer attr_readonly
  attribute serialize store store_accessor
].freeze
ENUMS =
%w[enum].freeze
ASSOCIATIONS =
%w[
  belongs_to has_one has_many has_and_belongs_to_many
  has_one_attached has_many_attached
].freeze
VALIDATIONS =
%w[
  validates validates_acceptance_of validates_associated
  validates_comparison_of validates_confirmation_of validates_each
  validates_exclusion_of validates_format_of validates_inclusion_of
  validates_length_of validates_size_of validates_numericality_of
  validates_presence_of validates_uniqueness_of validates_with
  validate
].freeze
CALLBACKS =
%w[
  after_initialize after_find after_touch
  before_validation after_validation
  before_save around_save
  before_create around_create after_create
  before_update around_update after_update
  after_save
  before_destroy around_destroy after_destroy
  before_commit after_commit after_rollback
  after_save_commit after_create_commit after_update_commit after_destroy_commit
].freeze
OTHERS =
%w[
  encrypts normalizes delegate delegate_missing_to
  accepts_nested_attributes_for has_secure_password
  has_secure_token generates_token_for composed_of
].freeze