简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM