首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >继承Ruby中的类级实例变量?

继承Ruby中的类级实例变量?
EN

Stack Overflow用户
提问于 2012-05-24 06:24:48
回答 3查看 7.9K关注 0票数 19

我想要一个子类从它的父类继承一个类级实例变量,但是我似乎不能理解。基本上,我正在寻找这样的功能:

代码语言:javascript
复制
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

然后我希望输出如下所示:

代码语言:javascript
复制
> 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给出了我想要的行为...而是一个类变量。

我觉得我的要求可能太高了。有什么想法吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-05-24 08:50:49

使用混合:

代码语言:javascript
复制
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)设置一个类级实例变量。

票数 6
EN

Stack Overflow用户

发布于 2012-05-24 08:18:19

Rails将其作为名为class_attribute的方法内置于框架中。您可以随时查看source for that method并制作自己的版本或逐字复制它。唯一需要注意的就是你的don't change the mutable items in place

票数 12
EN

Stack Overflow用户

发布于 2012-11-13 07:28:18

我在使用resque的项目中所做的就是定义一个基础

代码语言:javascript
复制
class ResqueBase
  def self.inherited base
    base.instance_variable_set(:@queue, :queuename)
  end
end

在其他子作业中,将默认设置队列实例。希望能有所帮助。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10728735

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档