为什么要使用实例变量来“连接"?控制器的意见? [英] Why use instance variables to "connect" controllers with views?

查看:66
本文介绍了为什么要使用实例变量来“连接"?控制器的意见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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?

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

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?

推荐答案

从某种意义上讲,您可以说它正在破坏封装.我发现如果您不小心,很容易在Rails中将业务/表示逻辑混合在一起.它通常在我编写视图模板时开始,发现我需要一些未从控制器传递的值.因此,我回过头来调整控制器,使其适合视图中的需求.一次又一次地调整之后,您将查看controller方法,它将设置所有类型的实例变量,除非您查看视图以了解其用途,否则这些实例变量是没有意义的.因此,最终您将需要同时查看控制器和视图以了解其中的一种,而不是能够孤立地使用一个或另一个.

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.

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

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.

这篇关于为什么要使用实例变量来“连接"?控制器的意见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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