ruby使用mixin设置动态类变量
我需要定义一些类变量来设置名称空间和表类变量 这是我正在使用的mixin模板:ruby使用mixin设置动态类变量,ruby,mixins,class-variables,Ruby,Mixins,Class Variables,我需要定义一些类变量来设置名称空间和表类变量 这是我正在使用的mixin模板: module MyMixin module ClassMethods .... end module InstanceMethods .... end def self.included(receiver) namespace, table = receiver.name.underscore.pluralize.split
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
对于下面的代码,我希望使用名称空间的类变量:“再见”和表:“朋友”
module Hello
class World
include MyMixin
end
end
module Goodbye
class Friend
include MyMixin
end
end
我尝试使用receiver.class\u variable\u set/get,但是当我加载再见::朋友代码时,Hello::World的类变量
如何设置和分离这两个类变量?我意识到我可以使用实例变量为通过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
receiver.instance_variable_set :@namespace, namespace.to_sym
receiver.instance_variable_set :@table, table.to_sym
receiver.instance_variable_set :@properties, {}
end
end
Hello
与Hello
不同。请注意大写字母,并且对读者更加友好。@sawa你是什么意思?