Rails 3,当控制器使用大量会话信息时,有没有办法保持瘦控制器?

发布于 2024-10-20 07:47:42 字数 311 浏览 3 评论 0原文

我和其他人一样喜欢一个漂亮的瘦控制器。

但是我正在开发的应用程序通过 JSON 与远程系统进行广泛的对话,并且会话变量被广泛使用...每个小交互都是对数十种控制器方法之一的单独命中,以及 Rails 的内置会话跟踪跟踪所有状态。

因此,控制器有数十种方法,每个“交互”都有一个方法,并且这些方法广泛读取(有时写入)会话。

据我了解,如果您在模型方法中访问会话,那么您正在做一些可怕的“错误”...但是对于数十个控制器方法来说,每个控制器方法有 100 多行代码似乎也是“错误”的。

考虑到这种情况,胖控制器与访问会话的模型之间的最佳权衡是什么?

I like a nice skinny controller as much as the next guy.

But the app I'm working on talks extensively to a remote system via JSON, and the session variables are used extensively... each little interaction is a separate hit to one of dozens of controller methods, and rails' built-in session tracking keeps track of all the state.

Consequently, the controller has dozens of methods, one for each "interaction" and those methods extensively read (and sometimes write) the session.

It's my understanding that if you're accessing the session in your model methods you're doing something horribly "wrong" ... but having 100+ lines of code PER controller-method for dozens of controller methods seems "wrong" too.

Given that scenario, what IS the best tradeoff between fat controllers vs models that access the session?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梨涡 2024-10-27 07:47:42

我最近遇到了类似的问题。我正在编写的应用程序严重依赖于接受/返回 JSON 的远程 API。随后,我的应用程序中的模型非常少,而且我的控制器也相当长。

我最终在 lib/ 中编写了一个自定义解析器 module 并调用了模块(它处理了控制器中通常存在的许多逻辑)

考虑以下内容:

module RemoteParser
  def get_user(user_id)
    result = ActiveSupport::JSON.parse(NetHttp.get('http://www.example.com/'))
    session[:received_user] = true
  end
end

现在你的控制器又可以变得瘦了:

class SomeController < ApplicationController
  def index
    @user = RemoteParser::get_user(params[:id])
  end
end

我想补充一点,这是此类用途的一个令人难以置信的设计示例。如果您提供有关您的要求等的其他信息,我可以进一步帮助您。

I recently came across a similar problem. I was writing and application that depended heavily on a remote API that accepted/returned JSON. Subsequently, I had very few models in my application, and my controllers were quite lengthly.

I ended up writing a custom parser module in lib/ and made calls to the Module (which handled a lot of the logic that would normally exist in the controller)

Consider the following:

module RemoteParser
  def get_user(user_id)
    result = ActiveSupport::JSON.parse(NetHttp.get('http://www.example.com/'))
    session[:received_user] = true
  end
end

Now your controllers can be skinny again:

class SomeController < ApplicationController
  def index
    @user = RemoteParser::get_user(params[:id])
  end
end

I'd just like to add that this is an incredibly contrived example of such uses. If you provide additional information about what your requesting, etc, I can help you further.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文