6

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

module Outer
  class Inner; end
  class AnotherInner; end
end
class C
  import Outer: [:Inner, :AnotherInner]
  def f
    Inner
  end
end

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

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

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

4

1 回答 1

2
module Outer
  class Inner; end
  class AnotherInner; end
end

class C
  include Outer

  def f
    Inner
  end
end

C.new.f # => Outer::Inner

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

于 2012-08-09T21:24:47.337 回答