Rubocop: Ordering of mixins, constants, class methods, instance methods, inner classes

Created on 8 Nov 2017  路  2Comments  路  Source: rubocop-hq/rubocop

Are there rules in Rubocop to enforce ordering of different types of elements in a class?

Given I have a class

class MyClass
  include MyModule

  MY_CONSTANT = "Constant value".freeze

  class << self
    def find_by_name(name)
    end
  end

  def class.find_or_create_by(name)
  end

  attr_reader :name

  def initialize(name)
  end

  def full_name
  end

  NotFoundError = Class.new(ArgumentError)
end

That is:

  • all modules must be included in a common place (customizable order)
  • all constants must be defined in a common place (customizable order)
  • all class methods must be defined in a common place (customizable order)

    There are two forms class methods can be included, and both must be positioned here

  • All attribute accessors must be defined in a common place (customizable order)
  • Any class initialize must be defined as the first instance method
  • Any instance methods must be defined in a common place (customizable order)
  • Any inner classes must be defined in the bottom (this could be common for both 'real' inner classes and also inner classes which inherit exceptions.

Of course, in the proper Rubocop-spirit, the ordering could probably be configurable.

Also, if in Rails, the ordering of elements could probably also include

  • associations
  • validations

Two questions:

Can Rubocop help me to enforce a proper ordering?

Would this idea help you to better organized code?

duplicate feature request

Most helpful comment

There isn't, but it is our oldest open issue, and I know it's also at the top of @bbatsov's list of cops he'd like to have himself. 馃槈 (#1575)

Closing this as a duplicate for now. If you want to try and take a stab at this, feel free to open a PR. I imagine an initial implementation could be as simple as just checking that include and extend are at the top of the class. Just to get something to build on.

All 2 comments

There isn't, but it is our oldest open issue, and I know it's also at the top of @bbatsov's list of cops he'd like to have himself. 馃槈 (#1575)

Closing this as a duplicate for now. If you want to try and take a stab at this, feel free to open a PR. I imagine an initial implementation could be as simple as just checking that include and extend are at the top of the class. Just to get something to build on.

Thanks @Drenmi for linking the issues. I had a feeling it was somewhere there... just couldnt find it.

Was this page helpful?
0 / 5 - 0 ratings