繁体   English   中英

动态类加载:Ruby中的类是否有“method_missing”?

[英]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

Module#const_missing

http://apidock.com/ruby/Module/const_missing

我假设您可以(ab)使用它来满足您的需求。

有const_missing方法:它的工作方式与method_missing类似,但它与常量有关

http://ruby-doc.org/core/classes/Module.html#M000489

也许你可以rescue一个未定义的常量错误并加载/创建你的类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM