如何在 class_eval 块中定义类变量?我有以下内容:
module Persist
def self.included(base)
# base is the class including this module
base.class_eval do
# class context begin
@@collection = Connection.new.db('nameofdb').collection(self.to_s.downcase)
def self.get id # Class method
#...
end
end
end
# Instance methods follow
def find
@@collection.find().first
#...
end
end
class User
include Persist
end
class Post
include Persist
end
User 和 Post 类都:get在使用User.methodsor进行内省时显示Post.methods。这是有道理的,因为它们是在 class_eval 的上下文中定义的,并且正是我所需要的。同样,该方法:find显示为各个类的 instance_method。
然而,我认为是一个类变量,即@@collection,原来是一个模块级别的class_variable。当我反省User.class_variablesorPost.class_variables时,它们变成了空的。然而Persist.class_variables显示:@@collection。
这怎么可能?块内的上下文不是class_eval类的上下文。那么变量不应该@@collection在类而不是模块上定义吗?
此外, 的值@@collection始终是包含它的最后一个类的名称。所以在这种情况下,它始终是“帖子”,而不是“用户”。我认为这是因为它是一个模块级变量,它会在每次包含时发生变化。它是否正确?
最后,我将如何在这种情况下定义一个类变量,以便每个类都有自己的@@collection定义。