Class: RuboCop::Cop::Layout::OrderedMethods

Inherits:
RuboCop::Cop show all
Includes:
IgnoredMethods, RangeHelp
Defined in:
lib/rubocop/cop/layout/ordered_methods.rb

Overview

Examples:

EnforcedStyle: alphabetical (default)

# Check that methods are defined alphabetically.

# bad
def self.b; end
def self.a; end

def b; end
def a; end

private

def d; end
def c; end

# good
def self.a; end
def self.b; end

def a; end
def b; end

private

def c; end
def d; end

Constant Summary collapse

COMPARISONS =
{
  'alphabetical' => lambda do |left_node, right_node|
    (method_name(left_node) <=> method_name(right_node)) != 1
  end
}.freeze
ERR_INVALID_COMPARISON =
'Invalid "Comparison" config for ' \
"#{cop_name}. Expected one of: #{COMPARISONS.keys.join(', ')}".freeze

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.method_name(node) ⇒ Object



45
46
47
48
49
# File 'lib/rubocop/cop/layout/ordered_methods.rb', line 45

def self.method_name(node)
  return node.method_name unless node.send_type?

  node.first_argument.method_name
end

Instance Method Details

#autocorrect(node) ⇒ Object



51
52
53
54
# File 'lib/rubocop/cop/layout/ordered_methods.rb', line 51

def autocorrect(node)
  _siblings, corrector = cache(node)
  corrector.correct(node, @previous_node)
end

#on_begin(node) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/rubocop/cop/layout/ordered_methods.rb', line 56

def on_begin(node)
  start_node = node.children.find(&:class_type?)&.children&.last || node
  siblings, _corrector = cache(start_node)

  consecutive_methods(siblings) do |previous, current|
    unless ordered?(previous, current)
      @previous_node = previous
      add_offense(
        current,
        message: "Methods should be sorted in #{cop_config['EnforcedStyle']} order."
      )
    end
  end
end