我有几个有常数的类SCHEMA
class Consumable::ProbeDesign < Consumable
SCHEMA = {
"type": "object",
"properties": { },
"required": []
}
end
class DataModule::WaterDeprivationLog < DataModule
SCHEMA = {
"type": "object",
"properties": {
"water_amount": {"type": "decimal"},
"notes": {"type": "string"}
},
"required": []
}
end
它们是 STI 方案中基类的子类
class Consumable < ApplicationRecord
include SingleTableInheritable
end
class DataModule < ApplicationRecord
include SingleTableInheritable
end
然后我有一个模块,它需要为从包含该模块的类继承的所有类动态访问该常量
module SingleTableInheritable
extend ActiveSupport::Concern
included do
def self.inherited(subclass)
subclass.class_eval do
schema = subclass::SCHEMA # NameError: uninitialized constant #<Class:0x0000560848920be8>::SCHEMA
# then do some validations that rely on that schema value
end
super
end
end
end
但是在执行时以及在如何调用它的上下文中,它找不到模块并返回NameError: uninitialized constant #<Class:0x0000560848920be8>::SCHEMA
请注意,subclass.const_get("SCHEMA")
也失败了
编辑:这是一个加载顺序问题。在类上运行之后,该常量可用,因为随后加载了该类。但是通过尝试预先加载这个类,模块会在预先加载时从父类继承,并且模块代码仍然在设置常量之前运行。
是否有某种类似于继承的钩子,但它允许所有内容都预加载?