所以我尝试了以下代码:
ComplicatedClass
module InternalObjects
InternalThing = Struct.new(:name, :description)
end
end
class ComplicatedClass
module Operations
def operate_on_object
InternalThing.new
end
end
end
class ComplicatedClass
include InternalObjects
include Operations
def other_operate_on_object
InternalThing.new
end
end
然后使用cc = ComplicatedClass.new
,cc.other_operate_on_object
工作正常,但调用cc.operate_on_object
会导致NameError: uninitialized constant ComplicatedClass::Operations::InternalThing
显然,我可以选择没有InternalObjects
模块,只需在ComplicatedClass
中定义我的结构:
class ComplicatedClass
InternalThing = Struct.new(:name, :description)
include Operations
def other_operate_on_object
InternalThing.new
end
end
并没有问题,但是在其他地方重复使用相同的结构是令人讨厌的(并且可能导致初始化例程中的元编程作为变通方法)。
同样,我也可以在操作模块(new
)中命名ComplicatedClass::InternalThing.new
调用,但从代码重用的角度来看,它是非常不明智的。