5

如何在 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定义。

4

1 回答 1

5

一种方法是为类变量创建访问器方法。

module Persist
    def self.included(base)
        # Adds class methods from 'ClassMethods' to including class.
        base.extend(ClassMethods)
        base.class_eval do
            self.collection = Connection.new.db('nameofdb').collection(self.to_s.downcase)
            # ...
        end
    end
    module ClassMethods
        def collection=(value)
            @@collection = value
        end
        def collection
            @@collection
        end
    end
    # Instance methods follow
    def find
        self.class.collection.find().first
        #...
    end
end

class User
    include Persist
end

class Post
    include Persist
end

另一种方法是通过访问器class_variable_set等访问模块中包含类的类变量。

def self.included(base)
    base.class_eval do
        class_variable_set('@@collection', Connection.new.db('nameofdb').collection(self.to_s.downcase))
        # …
    end
end

我将尝试回答您的问题“这怎么可能?class_eval 块中的上下文不是类的上下文。”

class_eval方法确实使self引用它在给定块内被调用的类。这允许您调用类方法等。但是,类变量将在块绑定到的上下文中进行评估 - 这里是模块。

例如,尝试这样做:

class Foo
    @@bar = 1
end

Foo.class_eval { puts @@bar }

这将导致异常“NameError: uninitialized class variable @@bar in Object”。这里给定的块绑定到顶级命名空间“Object”的上下文。

于 2013-02-17T14:55:41.720 回答