[英]Dynamic class loading: Is there a “method_missing” for classes in Ruby?
在我正在研究的Rails应用程序上,我有一个与单表继承模型“Node”相关的模型“Type”:Node的任何可能的子类都被定义为types表中的Type。
现在可以在初始化程序中加载所有类,但我只想在需要时加载子类。
我能想到的最好的解决方案是对未初始化的常量进行回退,该常量将检查该常量是否可以表示应用程序中的类,类似于method_missing的类。
我想对如何以及在何处定义此逻辑提出一些建议,或者是否有更好的解决方案。
我不知道这是否是新的,但我认为值得补充。 可以使用缺少方法作为类方法
class Example
def method_missing(method_name, *arguments, &block)
puts 'needs this instance method'
end
def self.method_missing(method_name, *arguments, &block)
puts 'needs this class method'
end
end
有const_missing方法:它的工作方式与method_missing类似,但它与常量有关
也许你可以rescue
一个未定义的常量错误并加载/创建你的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.