On 08/17/2012 03:39 PM, Matt Wagner wrote:
On Fri, Aug 17, 2012 at 10:52:46AM +0200, Jirka Tomasek wrote:
I don't like the sentence "Don't use it for passing variables to
view. Never." which is actually one of the first things that any
Rails book teaches you.
Yes, that was the main source of my confusion.

I agree that we should try to reduce using
instance variables in controllers where possible to avoid cluttering
controllers with them.
As someone mentioned in another reply here, there are uses where you
really need them -- e.g., before_filters. Of course we should be
careful to not use instance variables where there's no need for them;
sometimes we'll mistakenly use an instance variable just within the
scope of a method, for example.

The blog post you sent points out the reusability of partials so
passing the variables as locals helps avoid requiring use of eg.
@post in all partials instances. Imho it depends on the desired use
of the partial.

We have discussed with Imre the alternative way to pass variables
from controller's action to view. It can be done similar way as with
partials:

   ...someactioncode...
   render :action => :index, :locals => {:post => post}
end


but I have never seen this used anywhere in controller and I assume
this is not the "Rails way".
Yes, this feels pretty weird to me. That whole line should be
unnecessary -- we're overriding the "Rails magic" to explicitly perform
the default behavior, except referencing the variable as a local one. If
anything, this seems _more_ error-prone to me than relying on instance
variables.
All magic in programming is magic at wrong place.
Relying on autovivified variables for passing values is
1) unsafe
2) unreadable
3) unmaintainable
4) spaghetti
This can cause hell especially when refactoring so you lose track of
which data comes from where. Then your variables became automagically
initialised to nil, and then kaboom.

Generally, you want to have variables of only one type.
Since types in ruby are not lifted with nil, then
by autovivification you have broken contract of returning correct data type.

Nice example of this missbehavior might be returning nil instead of [] when
method can't find any items in database (this is just an illustrative example).
So you have to check first if there is a nil in variable and only then you
can use it (for example call 'each' method on that).

When using locals, interpreter can much easier identify real source of problem, so you get error message stating that variable does not exist, instead of confusing error stating that you can't call something on nil, including much worse problem
when that 'something' called on nil passes without problems but produces
completely undesired result (i.e. hidden runtime bug & data corruption).

Convenience or (at least partial) correctness and safety?

PS: If this sounds rude, I apologise, it was not meant like that.

- maros

Reply via email to