【问题标题】:ruby set Dynamic Class variables with mixinsruby 使用 mixins 设置动态类变量
【发布时间】:2016-03-12 15:08:08
【问题描述】:

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

这是我正在使用的 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

对于下面的代码,我希望有 namespace: 'hello'table: 'worlds'

的类变量
module Hello
    class World
        include MyMixin
    end
end

对于下面的代码,我希望有 namespace: 'goodbye'table: 'friends'

的类变量
module Goodbye
    class Friend
        include MyMixin
    end
end

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

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

【问题讨论】:

  • Hellohello 不同。请注意大小写,对读者更友好。
  • @sawa 你是什么意思?

标签: ruby mixins class-variables


【解决方案1】:

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

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
        receiver.instance_variable_set :@namespace, namespace.to_sym
        receiver.instance_variable_set :@table, table.to_sym
        receiver.instance_variable_set :@properties, {}
    end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-02-21
    • 2013-05-15
    • 1970-01-01
    • 2011-06-25
    • 2014-12-18
    • 2021-01-04
    • 2019-01-29
    • 1970-01-01
    相关资源
    最近更新 更多