Class: RuboCop::Cop::Rails::OrderedMacros

Inherits:
Base
  • Object
show all
Defined in:
lib/rubocop/cop/rails/ordered_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.

‘:through` associations are sorted as a separate trailing group (a `:through` association must be declared after its target association), not interleaved with the regular declarations.

Other exceptions (lifecycle callbacks, other dependency-ordered items) 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



34
35
36
# File 'lib/rubocop/cop/rails/ordered_macros.rb', line 34

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

Instance Method Details

#on_class(node) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rubocop/cop/rails/ordered_macros.rb', line 38

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

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

  MACROS.each do |macro|
    calls = statements.select { |statement| macro_call?(statement, macro) }
    regular, through = calls.partition { |call| !through_option?(call) }
    flag_unsorted(regular)
    flag_unsorted(through)
  end
end