Checking if variables are defined in Rails Partial Views

During this week I was working on a Rails app when I ran into an issue where I needed to check if a variable has been defined in my view. The standard way to check if a variable is defined in Ruby is with the defined? operator.

defined? name
# nil
name = "Bob"
defined? name
# "local-variable"

However, I remember reading something in The Rails 3 Way about not being able to do this in partial views. Apparently there is an implementation restriction in the rendering system, and we need to use the local_assigns hash.

<% if local_assigns.has_key? :name %>
  <p><%= name %></p>
<% end %>

I tried to find out what exactly the restriction is, but the only reference I could find was in the Rails API (under Passing local variables to sub templates).

Testing using defined? headline will not work. This is an implementation restriction.

I guess it’s just one of those things we need to remember. Happy coding.