Definition of class variables inside class_eval inside module # included

How to define class variables inside class_eval block? I have the following:

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

The User and Post classes are both shown :getin introspection with User.methodsor Post.methods. This makes sense as they are defined in the context of class_eval and exactly what I need. Similarly, a method is :findshown as an instance_method of individual classes.

However, what I considered a class variable, i.e. @@collectionturns out to be class_variable level. When I browse User.class_variablesor Post.class_variables, they become empty. However, it Persist.class_variablesshows :@@collection.

? class_eval . , @@collection , ?

, @@collection , . "", "". , , , . ?

, , @@collection.

+5
1

.

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

accessors 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: @@bar Object". "Object", .

+5
source

All Articles