如何在Ruby中将嵌套类"导入"当前类?

Ale*_*xey 6 ruby import namespaces ruby-on-rails

在Ruby中,我可以将模块/类嵌套到其他模块/类中.我想要的是在文件或类中添加一些声明,以便能够通过它们的短名称来引用嵌套类,例如Inner用来获取Outer::Inner,就像你在Java中那样,C#等.语法可能是这样的:

module Outer
  class Inner; end
  class AnotherInner; end
end
class C
  import Outer: [:Inner, :AnotherInner]
  def f
    Inner
  end
end
Run Code Online (Sandbox Code Playgroud)

简单的实现可能是这样的:

class Class
  def import(constants)
    @imported_constants = 
      (@imported_constants || {}).merge Hash[
        constants.flat_map { |namespace, names|
          [*names].map { |name| [name.to_sym, "#{namespace}::#{name}"] }
        }]
  end

  def const_missing(name)
    const_set name, eval(@imported_constants[name] || raise)
  end
end
Run Code Online (Sandbox Code Playgroud)

在Rails或某些gem中是否有可靠的实现,在与Rails的自动加载机制兼容的同时进行类似的导入?

Jör*_*tag 2

module Outer
  class Inner; end
  class AnotherInner; end
end

class C
  include Outer

  def f
    Inner
  end
end

C.new.f # => Outer::Inner
Run Code Online (Sandbox Code Playgroud)

请记住:Ruby 中不存在嵌套类之类的东西。类只是一个像任何其他对象一样的对象,并且它像任何其他对象一样被分配给变量。在这种特殊情况下,“变量”是模块内命名空间中的常量。然后,您可以将该常量添加到另一个模块(或类)的命名空间中,就像添加任何其他常量一样:通过include添加 module.