0
votes

Looking to have two tests on a variable, that might not be defined in a rails view.

<% if defined(:var) && var.present? %>
    <%= var.value %>
<% end %>

However, this is throwing a undefined local variable or method error when var is not defined. I assumed ruby/rails would short circuit the first expression and not try to evaluate the second, similar to python

>>> a = False
>>> a and b
False
>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

Any reason why short circuit is preceeding to the second evaluation?

2

2 Answers

4
votes

I think you want this:

if defined?(var) && var.present?

:var will always be defined as it's a symbol.

> defined?(:var)
=> "expression"
> defined?(var)
=> nil
> var = 1
=> 1
> defined?(var)
=> "local-variable"
1
votes

defined? expect you to pass the expression, not a Symbol. The Symbol will always return true.

2.1.5 :001 > defined? var
 => nil
2.1.5 :002 > defined? :var
 => "expression"
2.1.5 :003 > var = nil
 => nil
2.1.5 :004 > defined? var
 => "local-variable"

Hence

<% if defined?(var) && var.present? %>
  <%= var.value %>
<% end %>