类 (Classes)

优质
小牛编辑
125浏览
2023-12-01
  • 避免使用类变量(@@), 因为在继承的时候它们会有 "淘气" 的行为。

    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 # => 会输出"child"

    你可以看到在这个类的继承层级了,所有的类都共享一个类变量。 尽量使用实例变量而不是类变量。

  • def self.method 来定义单例方法(singleton methods). 这样在需要改类名的时候更方便.

    class TestClass
      # 错误
      def TestClass.some_method
        ...
      end
    
      # 正确
      def self.some_other_method
        ...
      end
  • 除非必要,避免写 class << self, 必要的情况比如 single accessors 和 aliased attributes。

    class TestClass
      # 错误
      class << self
        def first_method
          ...
        end
    
        def second_method_etc
          ...
        end
      end
    
      # 正确
      class << self
        attr_accessor :per_page
        alias_method :nwo, :find_by_name_with_owner
      end
    
      def self.first_method
        ...
      end
    
      def self.second_method_etc
        ...
      end
    end
  • public, protected, private 它们和方法定义保持相同缩进。 并且上下各留一个空行。

    class SomeClass
      def public_method
        # ...
      end
    
      private
    
      def private_method
        # ...
      end
    end