我有两个 Controller (比如 ArticlesController 和 PostsController),它们使用大约 5 个相同的方法。这是仅有的两个使用 5 种方法的 Controller ,因此它们不应该位于 ApplicationController 中。目前,我创建了一个基础 Controller (比如 ContentController),然后现有的两个 Controller 继承自该基础。
我的问题是 - 这是减少重复的最佳方法吗?
第二个问题 - 如何确保这些方法只能由继承自基础的 Controller 访问?在上面的示例中,我不希望直接访问 ContentController。
谢谢!
最佳答案
我认为拥有一个 ArticlesController 和 PostsController 都继承自的共同祖先是完全可以接受的。这就是继承的目的,不是吗?如果您不希望直接从 ContentController 公开操作,只需确保没有路由路由到 ContentController。
另一种方法是为这些功能制作一个模块,并根据需要包含该模块。假设您想将模块称为“我的功能”:
/lib/my_functions.rb:
module MyFunctions
def function1
...
end
def function2
...
end
...
end
然后在任何需要这些功能的地方只包含该模块:
class PostsController < ActionController::Base
include MyFunctions
...
end
class ArticlesController < ActionController::Base
include MyFunctions
...
end
关于ruby-on-rails - 在哪里找到多个 Rails Controller 使用的方法并限制对基本 Controller 的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4681440/