将现有的类添加到模块中 [英] Add existing classes into a module

查看:63
本文介绍了将现有的类添加到模块中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆