【问题标题】:Using methods from 2nd-level extended class [closed]使用二级扩展类的方法[关闭]
【发布时间】:2013-03-04 02:23:15
【问题描述】:

我正在尝试使用由该类扩展的类扩展的方法。我正在尝试做的一个例子:

class A
  def foo
    "Foobar"
  end
end

class B
  extend A
end

class C
  extend B
end

B.foo #=> "Foobar"
C.foo #=> "Foobar"

我不确定这种类型的功能在 Ruby 中是否可用。我知道这可以通过将B 中的extend 更改为include 来实现,但我希望A 中可用的方法可以作为BC 中的类方法。

【问题讨论】:

    标签: ruby inheritance mixins class-method


    【解决方案1】:

    extendinclude 用于模块;据我所知,您不能使用带有extendinclude 的模块(实际上Ruby 会引发错误)。相反,您应该将 A 定义为模块,然后将 extend B 和 C 与 A 一起定义。请参阅 John Nunemaker's RailsTips write-up on extendinclude 以更好地处理此设计模式。

    另一种选择是让 B 和 C 从 A 继承,如下所示:

    class A
      def self.foo
        "Foobar"
      end
    end
    class B < A; end
    class C < B; end
    

    【讨论】:

    • 哇,不知道为什么我以前没有想到这一点。这就是我最初尝试的方法,但我将我的方法定义为实例方法,而不是类方法。多哈。谢谢!
    【解决方案2】:
    class A
      def self.foo
        "Foobar"
      end
    end
    
    class B < A
    end
    
    class C < B
    end
    

    【讨论】:

      猜你喜欢
      • 2011-04-03
      • 1970-01-01
      • 1970-01-01
      • 2015-08-12
      • 1970-01-01
      • 2011-06-06
      • 2017-08-25
      • 2015-05-22
      • 1970-01-01
      相关资源
      最近更新 更多