【问题标题】:Ruby: Accessing calling child class constants from parent class?Ruby:从父类访问调用子类常量?
【发布时间】:2014-08-25 22:16:52
【问题描述】:

在 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::Basetest 除了常量之外的所有子类都一样吗?
  • @jstim 两者都是。 test() 是所有子类都应继承的方法,但依赖于每个子类之间不同的常量。

标签: ruby oop


【解决方案1】:

这似乎有效 - 它强制不断查找范围到当前实例的类

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 - 对于它的价值,我有兴趣阅读你必须写的东西。
猜你喜欢
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2012-02-19
  • 2023-03-21
  • 1970-01-01
相关资源
最近更新 更多