【发布时间】:2015-01-16 20:35:17
【问题描述】:
如果我有一堆看起来像这样的类:
module A
module B
module C
module D
class SpecificClass1
end
end
end
end
end
我不想像这样引用类
instance = A::B::C::D::SpecificClass1.new
一种方法是:
include A::B::C::D
instance = SpecificClass1.new
如果我想做这样的事情怎么办:
include A::B
instance = C::D::SpecificClass1.new
为什么这不起作用?它返回:
uninitialized constant C::D (NameError)
有没有办法有效地做我正在尝试的事情?
【问题讨论】:
-
无法复制。
-
顺便说一句,你有一个错字
instance = C::D::SpecifiClass1.new。SpecifiClass1应该是SpecificClass1 -
嗯,我过于简单的例子确实有效。所以我在我“拆分”模块层次结构的地方移动,在某些情况下它可以工作!我有一种预感,因为此类中的另一个必需文件具有相同的后缀,因此存在名称冲突?
-
我没有看到这个,也不知道这是不是一个好主意,但是你可以写
def specific_class1_instance; eval "A::B::C::D::SpecificClass1.new"; end来启用(在类中添加def m; puts 'hi'; end之后)specific_class1_instance.m #=> hi。我认为您不必担心这里的评估警察。 -
@CarySwoveland 为什么要使用
eval,因为你有合适的模块链,那么A::B::C::D::SpecificClass1.new就可以了。
标签: ruby namespaces