在哪里可以找到多个 Rails 控制器使用的方法?限制对基本控制器的访问
我有两个控制器(例如 ArticlesController 和 PostsController),它们使用大约 5 个相同的方法。这是唯一使用这 5 个方法的两个控制器,因此它们不应该位于 ApplicationController 中。目前,我创建了一个基本控制器(例如 ContentController),然后现有的两个控制器继承自该基本控制器。
我的问题是 - 这是减少重复的最佳方法吗?
第二个问题 - 如何确保这些方法只能由从基础继承的控制器访问?在上面的示例中,我不希望直接访问 ContentController。
谢谢!
I have two controllers (say ArticlesController and PostsController) that use about 5 of the same methods. These are the only two controllers that use the 5 methods, so they don't feel like they should be located in ApplicationController. Currently, I created a base controller (say ContentController) and then the existing two controllers inherit from this base.
My question is - is this the best approach to reducing duplication?
Second question - how to I ensure that these methods are only accessed by the controllers that inherit from the base? In the example above, I don't want ContentController to be accessed directly.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为拥有一个由 ArticlesController 和 PostsController 继承的共同祖先是完全可以接受的。这就是继承的目的不是吗?如果您不希望直接从 ContentController 公开操作,只需确保没有路由路由到 ContentController 即可。
另一种方法是为这些功能创建一个模块,并根据需要包含该模块。假设您想调用模块“我的函数”:
/lib/my_functions.rb:
那么无论您在哪里需要这些函数,只需包含该模块即可:
I think having a common ancestor that ArticlesController and PostsController both inherit from is totally acceptable. That's what inheritance is for isn't it? If you don't want the actions exposed directly from ContentController, simply make sure no routes route to ContentController.
Another way of doing it would be to make a module for those functions, and include that module as needed. Let's say you want to call the module "My Functions":
/lib/my_functions.rb:
Then wherever you need those functions just include that module: