将现有类添加到模块中 [英] Add existing classes into a module
本文介绍了将现有类添加到模块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 app/classes 文件夹中有一些现有的 ruby 类:
I have some existing ruby classes in a app/classes folder:
class A
...
end
class B
...
end
我想将这些类分组到模块 MyModule 中
I'd like to group those classes in a module MyModule
我知道我可以这样做:
module MyModule
class A
...
end
class B
...
end
end
但是有没有一个元编程快捷方式可以做同样的事情,所以我可以导入"所有现有的类?
but is there a meta programming shortcut that could do the same so I could "import" all the existing classes ?
谢谢,吕克
推荐答案
使用 const_missing
钩子.如果在当前模块中找不到该常量,请尝试在全局命名空间中解析:
Use the const_missing
hook. If the constant can't be found in the current module, try to resolve in the global namespace:
class A; end
class B; end
module M
def self.const_missing(c)
Object.const_get(c)
end
end
M::A.new
M::B.new
这篇关于将现有类添加到模块中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文