重构和解耦Rails控制器:它们可以互相调用吗? [英] Refactoring and Decoupling Rails controllers: can they call eachother?

查看:71
本文介绍了重构和解耦Rails控制器:它们可以互相调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Ruby on Rails应用程序中,我遇到以下情况:

I have the following situation in a Ruby on Rails app:


  • 用户填写表格(评论),可以看到一个omniauth页面,她可以在其中选择身份验证方法(openId,Twitter,Facebook等)。

  • omniauth已填写,成功用户返回后,将获得会话和初始表单数据被处理(发表评论)。

我都可以工作,除了我的逻辑分散在我认为的范围内。丑陋的方式 SessionsController 现在创建有关成功身份验证的注释。

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.

什么是解耦这样的好方法? Comment 模块是否应该挂接到(侦听)SessionsController?还是SessionsController应该简单地在 CommentsController Comment 类上调用某些方法以保存有关成功身份验证的注释?有什么我可以熟悉的模式可以解决这类问题吗?

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?

推荐答案

我不认为这是如果您在控制器之间具有共享功能,则可以使用继承或模块,这是从另一个控制器中调用一个控制器的最佳实践。对于您的特定问题,我愿意这样做:

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. 未经身份验证的用户POSTS到/ comments / create

  2. before过滤器检查身份验证并在会话中存储注释参数哈希和成功重定向位置,然后重定向到/ session / new

  3. 成功验证会话控制器后检查参数哈希并创建重定向到存储路径之前,所有延迟的模型。

如果可以从另一个请求中发布消息,那将是很好的选择,但是不幸的是,您可以't,因此您需要将逻辑放在会话控制器中。

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.

这篇关于重构和解耦Rails控制器:它们可以互相调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆