我想要实现:
class Model
table = "NOT SET"
self.get(id)
sql = "SELECT * FROM #{table} WHERE id = #{id}
end
end
这是我的通用模型类,带有示例函数。
class User < Model
table = "users"
end
我想将通用sql函数保留在父类中,因为在每个实例中都不需要它们。每个类声明都需要在运行get
函数时使用该表。
关于实例变量,你不需要实例[sic]来调用get
。类变量由层次结构中的类共享,因此也不起作用。
我该如何使用类变量?我怎样才能做到这一点?在java中,我会有一个受保护的变量,每个类在构造函数之上分配。
你可以这样做。提高Model类的硬错误将是确保在子类上实现table
的另一个好处。
此外,通过使用class << self
语法,您可以定义私有或受保护的类方法。
class Model
class << self
def get(id)
"SELECT * FROM #{table} WHERE id = #{id}"
end
private
def table
raise NotImplementedError
end
end
end
class User < Model
class << self
private
def table
"users"
end
end
end