Ruby on rails 如何";进口;在Ruby中将类嵌套到当前类中?
在Ruby中,我可以将模块/类嵌套到其他模块/类中。我想要的是在文件或类中添加一些声明,以便能够通过它们的短名称引用嵌套类,例如使用Ruby on rails 如何";进口;在Ruby中将类嵌套到当前类中?,ruby-on-rails,ruby,import,namespaces,Ruby On Rails,Ruby,Import,Namespaces,在Ruby中,我可以将模块/类嵌套到其他模块/类中。我想要的是在文件或类中添加一些声明,以便能够通过它们的短名称引用嵌套类,例如使用internal获取Outer::internal,就像在Java、C等中一样。语法可能如下所示: module Outer class Inner; end class AnotherInner; end end class C import Outer: [:Inner, :AnotherInner] def f Inner end
internal
获取Outer::internal
,就像在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
简单化的实现可能是这样的:
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的自动加载机制兼容的同时进行类似的导入
module Outer
class Inner; end
class AnotherInner; end
end
class C
include Outer
def f
Inner
end
end
C.new.f # => Outer::Inner
记住:Ruby中没有嵌套类。类和任何其他对象一样只是一个对象,它也像任何其他对象一样被分配给变量。在这种特殊情况下,“变量”是一个常量,它在模块内具有名称空间。将该常量添加到另一个模块(或类)的名称空间中的方法与添加任何其他常量的方法相同:通过
包含模块。我知道这种可能性。虽然1。我不想导入所有嵌套类。2.在Rails的上下文中,所有嵌套类都位于不同的文件中,通常需要指定Outer::Inner
,以便Rails知道从何处加载它。