Class: RuboCop::Cop::Obsession::MethodOrder

Inherits:
Base
  • Object
show all
Extended by:
AutoCorrector
Includes:
CommentsHelp, Helpers, VisibilityHelp
Defined in:
lib/rubocop/cop/obsession/method_order.rb

Overview

This cop checks for private/protected methods that are not ordered correctly. It supports autocorrect.

Code should read from top to bottom: methods should be defined in the same order as the order when they are first mentioned. Private/protected methods should follow that rule.

Note 1: public methods do not have to follow that rule, and can be defined in any order the developer wants, like by order of importance. This is because they are usually called outside of the class and often not called within the class at all. If possible though, developers should still try to order their public methods from top to bottom when it makes sense.

Note 2: method order cannot be computed for methods called by ‘send`, metaprogramming, private methods called by superclasses or modules, etc. This cop’s suggestions and autocorrections may be slightly off for these kinds of edge cases.

Note 3: for simplicity, protected methods do not have to follow that rule if there are both a protected section and a private section.

Note 4: for more information on this style of method ordering, see Robert C. Martin’s “Clean Code” book > “Chapter 3: Functions” > “One level of abstraction per function” > “Reading Code from Top to Bottom: The Stepdown Rule” chapter.

Examples:


# bad
def perform
  return if method_a?
  method_b
  method_c
end

private

def method_c; ...; end
def method_b; ...; end
def method_a?; ...; end

# good
def perform
  return if method_a?
  method_b
  method_c
end

private

def method_a?; ...; end
def method_b; ...; end
def method_c; ...; end

Defined Under Namespace

Classes: Node

Constant Summary collapse

MSG =
'Method `%<after>s` should appear below `%<previous>s`.'

Instance Method Summary collapse

Methods included from Helpers

#rails_callback?, #verb?

Instance Method Details

#on_class(class_node) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/rubocop/cop/obsession/method_order.rb', line 89

def on_class(class_node)
  @class_node = class_node
  find_private_node || return
  build_methods || return
  build_callback_methods

  build_method_call_tree
  build_ordered_private_methods
  build_private_methods

  verify_private_methods_order
end