问题描述
我仍在尝试清楚地了解Module/Class/Instance变量...
I am still trying to clearly understand Module/Class/Instance variables ...
我的代码当前看起来像这样...
My code currently looks something like this ...
module Foo
@@var1 ={}
@@var2 =[]
@@var3 = nil
def m1(value)
@@var2 << value
end
def m2(value)
@@var1[@@var3]=value
end
end
class Bar
include Foo
p @@var1
end
class Bar2
include Foo
p @var1
end
我正在尝试创建一个模块,该模块包含针对每个类的行为的类范围配置.配置存储在@@ var1和@@ var2中.使用此代码,变量可在包括该模块的所有类之间共享.这不是期望的结果,我希望每个类都具有自己的行为配置.
I am trying to create a module that contains a class-wide configuration for how each class will behave. The configuration is stored in @@var1 and @@var2. Using this code the variables are shared across ALL classes that include the module. This is not the desire result, I want each class to have it's own behavior configuration.
我还尝试创建一个包含模块的单个类,并创建变量,但是模块无法访问这些变量.
I have also tried creating a single class that includes the module and also creates the variables but then the variables are not accessible by the module.
module Foo
def m1(value)
@@var2 << value
end
def m2(value)
@@var1[@@var3]=value
end
end
class T
@@var1 ={}
@@var2 =[]
@@var3 = nil
include foo
end
class Bar < T
p @@var1
end
class Bar2 < T
p @var1
end
我还读到,拥有带有类变量的模块不是很好的编码风格,但是我想不出一种方法来实现此功能……
I have also read that having modules with class variables is not good coding style but I cannot think of a way to achieve my functionality with this ...
在此先感谢您的帮助
推荐答案
首先-类变量是邪恶的,应避免使用(因为它们也被所有子类继承,并且通常带来的弊大于利.
Firstly - class variables are evil and should be avoided (because they are also inherited by all subclasses and usually causes more harm than good.
您要在包含给定模块的类或模块上创建类实例变量(而非类变量).使用included
方法很容易:
You want to create a class instance variable (not class variable) on a class or module which is including given module. It is easy to do with included
method:
module Foo
@default_settings = {}
module ClassMethods
def foo_settings
@foo_settings
end
end
def self.included(target)
target.instance_variable_set('@foo_settings', @default_settings.dup)
target.extend ClassMethods
end
end
这篇关于红宝石中的模块和类变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!