Why use instance variables to "connect" controllers with views?
Asked Answered
D

2

9

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?

Doloroso answered 21/2, 2012 at 20:27 Comment(1)
@meggar, actually, it uses the variables directly. See BasicObject#instance_eval in the Ruby docs and you will see how this can be. Also check out Binding.Gannon
G
7

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.

Gannon answered 21/2, 2012 at 21:25 Comment(0)
S
4

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.

Spoof answered 21/2, 2012 at 21:7 Comment(1)
If I understood correctly the OP was referring to @variables while binding is useful to send variables to partial (in the locals). Interesting stuff, though.Edaphic

© 2022 - 2024 — McMap. All rights reserved.