Saturday, September 24, 2011

Setting optional local variables in your partials

Rails' partials are great - but sometimes, it's a hassle maintaining them.

For instance, haven't you ever changed the name of a partial, and consequently had to go find all your renderings of that partial and tediously adjust the name?

Or, have you ever decided to add a local variable requirement to a partial, and then have to, again, find all your renderings of that partial and then adjust the :locals => { :some_variable_I_now_have_to_set => "some value that shouldn't exist for most partials" } appropriately?

I don't have a solution to the first one (though I certainly wish I did), but I do - hooray! - for the second.

Basically, if you're thinking of doing something like this in your partial file...
<% unless optional_local_variable.nil? %>
  
<% end %>
...you'll encounter an error saying that "optional_local_variable" is not defined, which is quite disturbing, considering that you wanted to check if it was nil to begin with.

So what do you do instead?
<% unless local_assigns[:optional_local_variable].nil? %>
  
<% end %>

Voila. What does this mean you can do? Here's a more complete example:

books/index.html.erb:
Books
<%= render :partial=>"partials/book", :locals=>{ :books=>@books } %>

partials/_book.html.erb:
<% unless local_assigns[:books].nil? %>
  The 'books' variable was passed.
<% else %>
  The 'books' variable was not passed.
<% end %>

stores/index.html.erb:
Stores - Featured
<%= render :partial=>"partials/book" %>

The stores/index file's partial call doesn't require the local variable that was passed into the partial call in books/index. Useful.

Basically, if you want to make the specification of a local variable in the render :partial call optional, use local_assigns[:variable_name].nil? This also checks to see that variable_name is nil if you specify :locals=>{ :variable_name=>nil }.

1 comment:

  1. 11/11/11 at 11:00am or 11:00pm, kind of special...

    ReplyDelete

Please be considerate in what you say.