Classes

  • Avoid the usage of class (@@) variables due to their unusual behavior
    in inheritance.

    class Parent
      @@class_var = "parent"
    
      def self.print_class_var
        puts @@class_var
      end
    end
    
    class Child < Parent
      @@class_var = "child"
    end
    
    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.

    class TestClass
      # bad
      def TestClass.some_method
        # body omitted
      end
    
      # good
      def self.some_other_method
        # body omitted
      end
  • Avoid class << self except when necessary, e.g. single accessors and aliased
    attributes.

    class TestClass
      # bad
      class << self
        def first_method
          # body omitted
        end
    
        def second_method_etc
          # body omitted
        end
      end
    
      # good
      class << self
        attr_accessor :per_page
        alias_method :nwo, :find_by_name_with_owner
      end
    
      def self.first_method
        # body omitted
      end
    
      def self.second_method_etc
        # body omitted
      end
    end
  • Indent the public, protected, and private methods as much the
    method definitions they apply to. Leave one blank line above them.

    class SomeClass
      def public_method
        # ...
      end
    
      private
      def private_method
        # ...
      end
    end
  • Avoid explicit use of self as the recipient of internal class or instance
    messages unless to specify a method shadowed by a variable.

    class SomeClass
      attr_accessor :message
    
      def greeting(name)
        message = "Hi #{name}" # local variable in Ruby, not attribute writer
        self.message = message
      end
    end