适用于Ruby类在模块下进行扩展吗?

4

在Ruby中,类是否可以扩展自身但位于另一个模块中?例如,我有一个名为ErrorsController的类...

class ErrorsController < ApplicationController
 ....
end

但是如果在一个模块下,我希望有不同的行为。

class Share::ErrorsController < ErrorsController
 ....
end

这里的ErrorsController扩展了ErrorsController,这个没问题。但是我写成了长形式:

module Share
  class ErrorsController < ErrorsController
  end
end

有时似乎存在问题...


1
“there seemed to be problems”是什么意思?是否存在问题?而“sometime”又是什么意思?在什么时候似乎会出现问题? - Jörg W Mittag
你所说的"类扩展自身"是什么意思?在 Ruby 中是不可能的。一个类只能扩展一个现有的类,在类定义中给出继承子句,此时类尚不存在,因此它不能扩展自身。 - Jörg W Mittag
顺便说一句,如果你想知道某个语法是否有效,那么很容易自己找出来:只需输入并查看是否出现“SyntaxError”。或者,您可以使用 ruby -c检查语法)。 - Jörg W Mittag
2个回答

5
为了明确地引用“顶层”ErrorsController,通常的技巧是在它前面添加两个冒号。因此,例如:

module Share
  class ErrorsController < ::ErrorsController
  end
end

3
如果父级 ErrorsController 存储在其他模块中,则应使用完整路径。
例如:
module Share
  class ErrorsController < OtherModule::ErrorsController
  end
end

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接