在 Ruby 中继承类级实例变量? [英] Inherit class-level instance variables in Ruby?
问题描述
我希望子类从其父类继承类级实例变量,但我似乎无法弄清楚.基本上我正在寻找这样的功能:
I want a child class to inherit a class-level instance variable from its parent, but I can't seem to figure it out. Basically I'm looking for functionality like this:
class Alpha
class_instance_inheritable_accessor :foo #
@foo = [1, 2, 3]
end
class Beta < Alpha
@foo << 4
def self.bar
@foo
end
end
class Delta < Alpha
@foo << 5
def self.bar
@foo
end
end
class Gamma < Beta
@foo << 'a'
def self.bar
@foo
end
end
然后我希望它像这样输出:
And then I want this to output like this:
> Alpha.bar
# [1, 2, 3]
> Beta.bar
# [1, 2, 3, 4]
> Delta.bar
# [1, 2, 3, 5]
> Gamma.bar
# [1, 2, 3, 4, 'a']
显然,此代码不起作用.基本上我想为父类中的类级实例变量定义一个默认值,它的子类继承.子类中的更改将成为子子类的默认值.我希望这一切都发生,而不会影响一个类的值而影响其父级或兄弟级.Class_inheritable_accessor 给出了我想要的行为......但对于类变量.
Obviously, this code doesn't work. Basically I want to define a default value for a class-level instance variables in the parent class, which its subclasses inherit. A change in a subclass will be the default value then for a sub-subclass. I want this all to happen without a change in one class's value affecting its parent or siblings. Class_inheritable_accessor gives exactly the behavior I want... but for a class variable.
我觉得我可能要求太多了.有什么想法吗?
I feel like I might be asking too much. Any ideas?
推荐答案
使用 mixin:
module ClassLevelInheritableAttributes
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def inheritable_attributes(*args)
@inheritable_attributes ||= [:inheritable_attributes]
@inheritable_attributes += args
args.each do |arg|
class_eval %(
class << self; attr_accessor :#{arg} end
)
end
@inheritable_attributes
end
def inherited(subclass)
@inheritable_attributes.each do |inheritable_attribute|
instance_var = "@#{inheritable_attribute}"
subclass.instance_variable_set(instance_var, instance_variable_get(instance_var))
end
end
end
end
在一个类中包含这个模块,给它两个类方法:inheritable_attributes和inherited.
继承的类方法与所示模块中的 self.included 方法的工作方式相同.每当包含此模块的类被子类化时,它会为每个声明的类级可继承实例变量 (@inheritable_attributes) 设置一个类级实例变量.
Including this module in a class, gives it two class methods: inheritable_attributes and inherited.
The inherited class method works the same as the self.included method in the module shown. Whenever a class that includes this module gets subclassed, it sets a class level instance variable for each of declared class level inheritable instance variables (@inheritable_attributes).
这篇关于在 Ruby 中继承类级实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!