- 类 (Classes)
类 (Classes)
避免使用类变量(
@@),
因为在继承的时候它们会有 “淘气” 的行为。
[link]class Parent@@class_var = 'parent'def self.print_class_varputs @@class_varendendclass Child < Parent@@class_var = 'child'endParent.print_class_var # => 会输出"child"
你可以看到在这个类的继承层级了,所有的类都共享一个类变量。 尽量使用实例变量而不是类变量。
用
def self.method来定义单例方法(singleton
methods). 这样在需要改类名的时候更方便.
[link]class TestClass# 错误def TestClass.some_method...end# 正确def self.some_other_method...end
除非必要,避免写
class << self,
必要的情况比如 single accessors 和 aliased attributes。
[link]class TestClass# 错误class << selfdef first_method...enddef second_method_etc...endend# 正确class << selfattr_accessor :per_pagealias_method :nwo, :find_by_name_with_ownerenddef self.first_method...enddef self.second_method_etc...endend
public,protected,private它们和方法定义保持相同缩进。 并且上下各留一个空行。[link]class SomeClassdef public_method# ...endprivatedef private_method# ...endend
