Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

erb idiom to handle undefined variable

Tags:

ruby

erb

I'm trying to write some puppet .erb, I'd like to handle this "environment" variable if it's:

  • undefined
  • a string with newlines
  • an array.

I've got as far as this:

<% Array(environment).join("\n").split(%r{\n}).each do |f| %>
one line: <%= f %>
<% end %>

But haven't gotten around the undefined case yet. I've tried this

<% if (defined?(environment)).nil? %?
<% Array(environment).join("\n").split(%r{\n}).each do |f| %>
one line: <%= f %>
<% end %>
<% end %>

but am still getting "(erb):11: undefined local variable or method `environment' for main:Object (NameError)" when trying to test it like this:

ruby -rerb -e "environmentUNDEFINEME= [ 'cronvar=cronval', 'var2=val2' ]; 
puts ERB.new(File.read('templates/job.erb')).result"

Sorry this is so basic, but somebody's got to ask the easy questions. Any help?

like image 260
Kevin G. Avatar asked Oct 25 '25 17:10

Kevin G.


1 Answers

I would do this:

<% if defined?(environment) %>
  <% Array(environment).each do |f| %>
  one line: <%= f %>
  <% end %>
<% end %>

I didn't understand why you joining on new lines and then splitting on them again, so I removed it from the example.

like image 160
Ryan Bigg Avatar answered Oct 27 '25 09:10

Ryan Bigg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!