Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Feb 04

HOWTO: Call a nil :local variable from a partial

Posted by Sandro Paganotti in Ruby on Rails - comments are closed digg this add to delicious

Have you notice that if you try to execute a partial like the following:


# _my_name.rhtml
This is a partial and this is my name: <%=name%>

without calling it with a :name locale you are prompted this nice Exception ?


undefined local variable or method `name' for #<#<Class:0x542ae28>:0x542ad24>

The only way to avoid this exception is to execute a line of code that checks if the variable is nil and, in case of positive answer, it set that variable to nil! I know this could sound quite weird but it’s the only way I found to make thing work.

So, here is the line:


<%
# _my_name.rhtml
name = name.nil? ? false : name
%>

If someone know why this strange behavior happens please let me know.

Comments

  • marcus derencius

    Posted on February 04

    well, you can replace your code with: <%=name rescue nil%>
  • Nikos D.

    Posted on February 05

    Or you could also call: <% name ||= '' %> on the top of the partial (this is what i usually do)
  • Tarmo T.

    Posted on February 07

    One could also use local_assigns[:name].
  • Sunny

    Posted on February 20

    I think Nikos has the most rubiest way. <% name ||= nil %> is a little bit cleaner I think like that if(name) is false

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory