Reputation: 85
I'm trying to loop through and array and have checked to make sure it is being passed correctly to the template, yet am hitting the error.
The template:
<% if defined?(source[:blacklist]) %>
"blacklist": [
<% source[:blacklist].each do |listed| %>
"<%= listed %>"
<% end %>
],
<% end %>
output of source[:blacklist] when no loop:
"[\"/var/log/httpd/access.log*\", \"/var/log/httpd/error.log*\", \"/var/log/httpd/ssl_request_log\", \"/var/log/httpd/access_log\", \"/var/log/httpd/error_log\"]"
error:
undefined method `each' for nil:NilClass
Upvotes: 0
Views: 1953
Reputation: 361
Your array is not present, if it was it would actually be a string.
Using defined?(source[:blacklist])
presents an issue as it will return true if it's not an array, e.g. defined? nil
is "nil"
which is truthy.
If you cannot change how the data is being generated, parse it into a Ruby array, defaulting to an empty array if there is an unexpected data or none at all.
blacklist = source[:blacklist].gsub(/(\[\"|\"\])/, '').split('", "') || []
<% if not blacklist.empty? %>
Upvotes: 1
Reputation: 36860
If source[:blacklist]
is nil then defined? source[:blacklist]
will return the string "method" and that's "truthy".
So it will fall through and you'll get the error you see... Undefined method each for nil:NilClass
When you say "output of source with no loop"... is that in the controller or did you check the output in the erb file? It could be the value's not being passed to the erb, and you typically want to use instance variables to pass data to html.erb files.
Also, you should note that the output you show for source[:blacklist]
is actually a string, not an array, so even if it was passed you would still get an error on the each
method.
Upvotes: 0