将现有类添加到模块中

Luc*_*Luc 5 ruby module metaprogramming

我在app/classes文件夹中有一些现有的ruby类:

class A
   ...
end

class B
   ...
end
Run Code Online (Sandbox Code Playgroud)

我想在模块MyModule中对这些类进行分组

我知道我可以这样做:

module MyModule
  class A
      ...
   end
   class B
      ...
   end
end
Run Code Online (Sandbox Code Playgroud)

但是有一个元编程快捷方式可以做同样的事情,所以我可以"导入"所有现有的类?

谢谢,吕克

Ale*_*yne 9

module Foo
  A = ::A
  B = ::B
end

Foo::A.new.bar
Run Code Online (Sandbox Code Playgroud)

Note that the :: prefix on a constant starts searchign the global namespace first. Like a leading / on a pathname. This allows you differentiate the global class A from the modularized constant Foo::A.


hor*_*guy 5

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
Run Code Online (Sandbox Code Playgroud)