Noob syntax question

Hey everyone,

I’m just solidifying my understanding of ruby “example by example”.
Can someone let me know if I understand this correctly…

In my view I have the following…

<%= render :partial => “sidebar” ,
:locals => { :recent_messages => @recent_messages } %>

Am I correct when I say that I’m passing the “@recent_messages” as an
instance variable to the new partial? For example, in the new partial
if I did this…

<%= render :partial => “sidebar” ,
:locals => { :foo => @recent_messages } %>

Then “:foo” would be the instance variable that is available for use
in the partial. I’m simply passing the @recent_messages to that
instance variable name correct?

I just want to be sure I don’t have that backwards. I keep thinking
that @recent_messages is an instance variable, but it’s actually an
@variable.

Thanks!

Chris

Hi –

On Mon, 20 Jul 2009, internetchris wrote:

:locals => { :recent_messages => @recent_messages } %>
instance variable name correct?

I just want to be sure I don’t have that backwards. I keep thinking
that @recent_messages is an instance variable, but it’s actually an
@variable.

@recent_messages is an instance variable. Anything identifier that
starts with a single ‘@’ is an instance variable.

When you do this:

:locals => { :foo => @recent_messages }

your setting this up so that in your partial, you will have a local
variable called foo, initialized to the value of @recent_messages. So
you can then do things like:

<% foo.each do |message| %>

<% end %>

However, since @recent_messages is an instance variable, it’s actually
going to be visible in the partial already. In other words, you can
drop that :foo thing and do this in the partial, if you want:

<% @recent_messages.each do |message| %>

and so forth.

So there are two things going on here: the instance variable itself
(which is visible in the master template and the partial), and the
local variable “foo” in the partial, which you have initialized to the
same value as @recent_messages. If you use “recent_messages” instead
of “foo”, then you’ll get a local variable of that name in the
partial.

David


David A. Black / Ruby Power and Light, LLC
Ruby/Rails consulting & training: http://www.rubypal.com
Now available: The Well-Grounded Rubyist (The Well-Grounded Rubyist)
Training! Intro to Ruby, with Black & Kastner, September 14-17
(More info: http://rubyurl.com/vmzN)

Many thanks!

I did have it backwards. I felt uncomfortable describing it to myself
so I thought I better ask.

Chris