为什么使用实例变量来“连接”有视图的控制器?

发布于 2025-01-07 09:54:10 字数 201 浏览 0 评论 0原文

这是一个概念性问题,我在 SO 中找不到答案,所以我在这里:

为什么使用实例变量来连接控制器和视图?难道我们没有两个不同类的两个不同对象(控制器与视图)。那么,当渲染视图时,我们处于不同的上下文中,但我们正在使用另一个对象的实例变量?这不是以某种方式破坏封装吗?

Rails 如何设法将一个对象匹配到另一个对象?它是否将控制器的所有实例变量克隆到视图中?

This is a conceptual question and I haven't been able to find the answer in SO, so here I go:

Why instance variables are used to connect controllers and views? Don't we have two different objects of two different classes (Controller vs Views). So, when the view is rendered we are in a different context, but we are using instance variables of another object? Isn't this breaking encapsulation in somehow?

How does Rails manage to do that matching from one object to another? Does it clone all the instances variables of the controller to the view?

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

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

发布评论

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

评论(2

浅笑依然 2025-01-14 09:54:10

从某种意义上说,你可以说它破坏了封装。我发现,如果你不小心,很容易将你的业务/表示逻辑混合在 Rails 中。它通常在我编写视图模板时开始,并发现我需要一些未从控制器传递的值。所以我返回并调整控制器以适应我在视图中需要的内容。经过一次又一次的调整后,您查看控制器方法,它正在设置各种实例变量,除非您查看视图以了解它们的用途,否则这些变量没有意义。因此,您最终会遇到这样的情况:您需要同时查看控制器和视图才能理解其中之一,而不是能够孤立地看待其中一个。

我认为使用实例变量(与 Binding 技巧一起)只是一种将所需的任何值从控制器传递到视图的方法,而无需提前声明参数(就像定义方法时那样) )。没有声明意味着需要编写的代码更少,并且当您想要重构和重新组织事物时需要更改的代码也更少。

In a sense, you could say that it is breaking encapsulation. I have found that if you are not careful, it is easy to get your business/presentation logic mixed together in Rails. It usually starts when I am writing a view template, and discover that I need some value which I didn't pass from the controller. So I go back, and tweak the controller to suit what I need in the view. After one tweak, and another, and another, you look at the controller method, and it is setting all kinds of instance variables which don't make sense unless you look at the view to see what they are for. So you end up in a situation where you need to look at both controller and view to understand either, rather than being able to take one or the other in isolation.

I think that using instance variables (together with the Binding trick) is simply a way to pass whatever values you need from controller to view, without having to declare parameters in advance (as you would when defining a method). No declarations means less code to write, and less to change when you want to refactor and reorganize things.

苏璃陌 2025-01-14 09:54:10

Rails 使用 evalBinding 将控制器实例变量传递给视图。请参阅 Dave Thomas 的演示,第 46 分钟有一个小示例,解释了如何执行此操作完成了。

Rails uses eval and Binding to pass controller instance variables to views. See this presentation from Dave Thomas, there's a small example at minute 46' that explains how this is done.

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