Ruby:如何从父类访问调用子类的常量?

5
在Ruby中,我如何从父类访问调用类的常量?
Module Foo
  class Base
    def test()
      #how do I access calling class's constants here?
      #ex: CallingClass.SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end

你是否有许多其他的类继承了Foo::Base,并拥有它们自己不同的常量?除了常量之外,所有子类的test方法是否都相同? - jstim
@jstim 是的,两者都是。test() 是所有子类都应该继承的方法,但它依赖于每个子类之间不同的常量。 - doremi
1个回答

13

这似乎有效 - 它强制将查找限定在当前实例的类中

module Foo
  class Base
    def test
      self.class::SOME_CONST
    end
  end
end

class Bar < Foo::Base
  SOME_CONST = 'test'
end

Bar.new.test # => 'test'

写了100行关于模板和策略模式,我很高兴这在这里。 - jstim
@jstim - 说实话,我很感兴趣阅读你所写的内容。 - doremi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接