Classes

  • Avoid the usage of class (@@) variables
    due to their “nasty” behavior in inheritance.
    [link]

    1. class Parent
    2. @@class_var = 'parent'
    3. def self.print_class_var
    4. puts @@class_var
    5. end
    6. end
    7. class Child < Parent
    8. @@class_var = 'child'
    9. end
    10. Parent.print_class_var # => will print "child"

    As you can see all the classes in a class hierarchy actually share one
    class variable. Class instance variables should usually be preferred
    over class variables.

  • Use def self.method to define singleton
    methods. This makes the methods more resistant to refactoring changes.
    [link]

    1. class TestClass
    2. # bad
    3. def TestClass.some_method
    4. ...
    5. end
    6. # good
    7. def self.some_other_method
    8. ...
    9. end
  • Avoid class << self except when necessary,
    e.g. single accessors and aliased attributes.
    [link]

    1. class TestClass
    2. # bad
    3. class << self
    4. def first_method
    5. ...
    6. end
    7. def second_method_etc
    8. ...
    9. end
    10. end
    11. # good
    12. class << self
    13. attr_accessor :per_page
    14. alias_method :nwo, :find_by_name_with_owner
    15. end
    16. def self.first_method
    17. ...
    18. end
    19. def self.second_method_etc
    20. ...
    21. end
    22. end
  • Indent the public, protected, and
    private methods as much the method definitions they apply to. Leave one
    blank line above and below them.[link]

    1. class SomeClass
    2. def public_method
    3. # ...
    4. end
    5. private
    6. def private_method
    7. # ...
    8. end
    9. end