I’m questioning what appears to be a recommendation that makes no sense
in AWDWR 2nd Ed. I get the point being made, but the actual
convention/implementation seems to make the point ineffective.
If I have a controller Company with an action aboutus and an instance
var of @contactInfo (a hash), and I have a view called aboutus.rhtml
which renders a partial _contactus.rhtml, I could simply use the
@contactInfo instance var inside _contactsus.rhtml.
So, about doing that, AWDWR on page 125 says:
– In the layout, we have access to the @cart instance variable that
was set by the controller. It turns out that this is also available
inside partials called from the layout. However, this is a bit like
calling a method and passing it some value in a global variable. It
works, but it’s ugly coding, and it increases coupling (which in turn
makes your programs brittle and hard to maintain).
I think for many thing this likely isn’t necessary in practice for
things that are obviously going to be coupled anyway, but I get it. A
view might as well be abstracted the same way any method would be. At
least you’d want that option.
But here’s my problem…
On page 510 the book says:
– Idiomatic Rails developers use a variable named after the template
(article in this instance). In fact, it’s normal to take this a step
further. If the object to be passed to the partial is in a controller
instance variable with the same name as the partial, you can omit the
:object parameter.
OK, so what that says is if I have a controller Company with an action
aboutus and an instance var of @contactInfo (a hash), and I have a view
called aboutus.rhtml which renders a partial _contactInfo.rhtml (same
name as the instance var this time), then the render command can simply
be this:
<%= render :partial => “contactInfo” %>
Instead of having to write this:
<%= render :partial => “contactInfo”, :object => @contactInfo %>
So now we have a partial using the code contactInfo[‘phone’] instead of
@contactInfo[‘phone’].
If you ask me, the fact that we required the instace var to be named
contactInfo, and the partial to be named contactInfo and then the local
variable to be named contactInfo has created a higher degree of
interdependence than if we just used the instance var directly in the
partial.
If I decide to change the instance var name in the controller, that is
going to break the partial code in both cases. If I use the shortcut
idiom and I changethe instance var, then I have to changethe name of the
partial too. Where else might that break. But if I use the instance var
directly in the partial, and changethe ivar name, then all I haveto do
search & replace occurrences of that ivar name. Easy. fast, and fewer
surprises as far as I can tell.
So, what about this convention/idiom according to “the Daves” have I
missed?
– gw