重构和解耦 Rails 控制器:它们可以互相调用吗?
我在 Ruby on Rails 应用程序中遇到以下情况:
- 用户填写表单(评论),看到一个omniauth 页面,她可以在其中选择身份验证方法(openId、Twitter、Facebook 等)。
- 填写omniauth后,用户成功返回后,将获取会话并处理初始表单数据(发布评论)。
我一切都在工作,只是我的逻辑以一种我认为丑陋的方式散布开来; SessionsController
现在创建有关成功身份验证的注释。
解耦这样的事情的好方法是什么? Comment
模块是否应该挂接到(监听)SessionsController 中?或者 SessionsController 是否应该简单地调用 CommentsController
或 Comment
类上的一些方法来保存成功身份验证后的评论?有没有我可以熟悉的模式来解决此类问题?
I have the following situation in a Ruby on Rails app:
- user fills in a form (a comment), gets to see an omniauth page where she can choose the authentication method (openId, Twitter, Facebook and the likes).
- omniauth is filled in, on success user returns, gets a session and the initial form data is processed (comment is published).
I all works, except that I have my logic spread around in, what I consider, an ugly way; the SessionsController
now creates the comment on successfull authentication.
What is a good way to decouple things like this? Should the Comment
module hook into (listen to) the SessionsController? Or should the SessionsController simply call some methods on the CommentsController
or Comment
class to save a comment on successfull authentication? Are there any patterns that I can get myself familiar with, that solve these kind of issues?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为,如果控制器之间共享功能(使用继承或模块),那么从一个控制器调用另一个控制器不一定是一种好的做法。对于您的具体问题,我会这样做:
如果您可以从另一个请求进行 POST,那就太好了,但不幸的是您不能,因此您需要将逻辑放入会话控制器中。
I don't think it's necessarily good practice to call one controller from another, if you have shared functionality between controllers either use inheritance or a module. For your specific problem I'd do:
What would be great is if you could POST from another request, but unfortunately you can't, so you'll need to put the logic in the session controller.