在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
答案 0 :(得分: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'
答案 1 :(得分:0)
如果你想获得子类中定义的所有常量及其值,你可以这样做:
module Foo
class Base
def test
constants = self.class.constants
constants.zip(constants.map { |c| self.class.const_get(c) }).to_h
end
end
end
class Bar < Foo::Base
SOME_CONST = 'test'
ANOTHER_CONST = 'quiz'
end
Bar.new.test #=> {:SOME_CONST=>"test", :ANOTHER_CONST=>"quiz"}