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

dor*_*emi 3 ruby oop

在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
Run Code Online (Sandbox Code Playgroud)

Nik*_*nov 7

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

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'
Run Code Online (Sandbox Code Playgroud)