Class: RuboCop::Cop::Rails::AlphabeticalMacros

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/alphabetical_macros.rb

Overview

Requires class-level macro declarations of the same kind to be sorted alphabetically by their first symbol argument. Checked per macro name: all ‘belongs_to` sorted among themselves, all `validates` sorted, etc.

Exceptions (lifecycle callbacks, dependency-ordered items, logical grouping) are NOT modelled — this is an experimental cop; if it flags more legitimate cases than it helps, drop it.

Examples:

# bad
validates :name
validates :email

# good
validates :email
validates :name

Constant Summary collapse

MSG =
'Sort `%<macro>s` declarations alphabetically (`%<name>s` should come before `%<previous>s`).'
MACROS =
%i[belongs_to has_one has_many has_and_belongs_to_many validates scope].freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.default_configurationObject



30
31
32
# File 'lib/rubocop/cop/rails/alphabetical_macros.rb', line 30

def self.default_configuration
  super.merge('Include' => ['app/models/**/*.rb'])
end

Instance Method Details

#on_class(node) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/rubocop/cop/rails/alphabetical_macros.rb', line 34

def on_class(node)
  body = node.body
  return unless body

  statements = body.begin_type? ? body.children : [body]

  MACROS.each do |macro|
    flag_unsorted(statements.select { |statement| macro_call?(statement, macro) })
  end
end