ruby使用mixins设置动态类变量

时间:2016-03-12 15:08:08

标签: ruby mixins class-variables

我需要定义一些设置名称空间和表类变量的类变量。

这是我使用的mixin模板:

module MyMixin
    module ClassMethods
        .... 
    end

    module InstanceMethods
        ....
    end

    def self.included(receiver)
        namespace, table = receiver.name.underscore.pluralize.split('/')
        receiver.extend         ClassMethods
        receiver.send :include, InstanceMethods
    end
end

对于下面的代码,我希望有命名空间的类变量:' hello' 表:' worlds'

module Hello
    class World
        include MyMixin
    end
end

对于下面的代码,我希望有命名空间的类变量:'再见' 表:'朋友'

module Goodbye
    class Friend
        include MyMixin
    end
end

我尝试使用receiver.class_variable_set / get但是当我加载 Goodbye :: Friend 代码时, Hello :: World 的类变量。

如何设置和分隔两个类变量?

1 个答案:

答案 0 :(得分:0)

我意识到我可以使用instance_variables为通过mixin模板实例化的类保留单独的" class" 变量。

\x20