Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo if variable is defined in ruby/erb [duplicate]

Tags:

ruby

erb

Possible Duplicate:
Checking if a variable is defined in Ruby

using Tilt's template render method, I pass in

#... t setup ...
t.render(self, { :a => 'test', :b => 'again' })

in my template.erb

<%= a %>
<%= b %>

say I remove :b from the hash that I pass to the template. The render will fail because :b is undefined.

in PHP, I could go:

<?= isset($foo) ? $foo : '' ?>

is there any clean way (in ruby/erb) to "echo if"?

I tried <%= b.nil? ? b : '' %> but that is obviously wrong.. Any help would be appreciated

like image 753
tester Avatar asked Oct 15 '12 23:10

tester


2 Answers

defined? is the ruby equivalent to isset().

<%= defined?(a) ? a : 'some default' %>
like image 56
Alex Wayne Avatar answered Sep 28 '22 09:09

Alex Wayne


If you want to display nothing if a is not defined :

<%= a if defined?(a) %>

Also what you can do is set some default to a at the beginning of your partial if it's not defined. This way, you're assured that a won't crash on you and you don't have to test if it's defined everywhere. I prefer this way personally.

CAUTION : if you set a to false when you pass it to the template, it'll be reassigned to "" in my example .

<% a ||= "" %>
#Then do some things with it. No crash!
<%= a %>
<%= a*10 %>
<%= "Here's the variable a value: #{a}" %>
like image 33
Anthony Alberto Avatar answered Sep 28 '22 09:09

Anthony Alberto