Reputation: 65
I have an erb file with a lot of these and I am trying to create a loop for them:
<% if @addhostgroup -%>
<% @addhostgroup.each do |k, v| %>
<%= k %> <%= v %>
<% end %>
<% end %>
<% if @addservicegroup -%>
<% @addservicegroup.each do |k, v| %>
<%= k %> <%= v %>
<% end %>
<% end %>
What I want to do is something like this:
<% %w(addhostgroup addservicegroup).each do |action| %>
<% if @action -%>
<% @action.each do |k, v| %>
<%= k %> <%= v %>
<% end %>
<% end %>
<% end %>
Can somebody tell me how to use variables on erb variables names?
I was searching for a way without success.
Thank you very much!
Upvotes: 1
Views: 1806
Reputation: 2214
The problem is that block variable action
holds a string with the name of the action. You want to call @variable
with dynamic name based on the name. You are searching for this piece of code:
instance_variable_get("@#{action}")
Upvotes: 2
Reputation: 1320
Edit: An easier way would be to make a normal array instead of a percent literal. [@addhostgroup, @addservicegroup].each do |action|
. Sometimes I over look the little things :)
You can use instance_variable_get along with the array and iteration into action
that you have setup.
Add a line immediately inside the each block with:
<% instance_var_value = instance_variable_get(:"@#{action}") %>
You could also map the values into the array before iterating over it.
Upvotes: 4