Brando__ Brando__ - 1 year ago 82
Ruby Question

ERB template nested variable - accessing a hash key based on array element

I have the following data and erb template: a hash mapping services to port numbers and an array of services.

I iterate over the array for each service and I need to access the hash to get the port number for the currently being processed service. I don't seem to be allowed to nest variables the way I am doing below. Is there a better way?

ports = {"max-api" => 83, "max-logger" => 82, "max-data" => 84}

services = %w( max_api max_data max_logger )

<% @services.each do |service| %>
<% if service.include?("max_logger") %>
shell: echo <%= service %>:<%= @ports["<%= service %>"] %>
<% else %>
shell: echo <%= service %>:<%= @ports["<%= service %>"] %>00
<% end %>
<% end %>


Simplest possible example I have the erb template

<% @services.each do |service| %>
<%= @ports[<%= service %>] %>
<% end %>


If I try to run my code I get the following error:

Chef::Mixin::Template::TemplateError
------------------------------------
(erubis):2: syntax error, unexpected '<', expecting ']'
_buf << ( @ports[<%= service ).to_s; _buf << ']...
^
(erubis):2: unterminated string meets end of file

Answer Source

I realized lately they won't work if they don't match in name (array value, hash key):

{"max-api" => 83, "max-logger" => 82, "max-data" => 84}

They differ in - and/or _ from @services:

%w( max_api max_data max_logger )

Just tweaked a bit @services:

ports = {'max-api' => 83, 'max-logger' => 82, 'max-data' => 84}
services = %w(max-api max-data max-logger)

services.each do |service|
  puts "shell: echo #{service}:#{ports[service]}#{'00' if service != 'max-logger'}"
end
# => shell: echo max-api:8300
# => shell: echo max-data:8400
# => shell: echo max-logger:82
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download