Refactoring and Decoupling Rails controllers: can they call eachother?

[亡魂溺海] 提交于 2019-12-11 18:07:34

问题


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?


回答1:


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:

  1. Unauthenticated user POSTS to /comments/create
  2. A before filter checks for authentication and stores the comment params hash and the success redirect location in the session then redirects to /session/new
  3. Upon successfully authenticating the session controller checks the params hash and creates any deferred models before redirecting to the stored path.

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.



来源:https://stackoverflow.com/questions/5233764/refactoring-and-decoupling-rails-controllers-can-they-call-eachother

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!