Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output ruby array via an erb template

I'm using puppet to provide a set of constants for a ruby program. I need to provide an array of hostnames over which my program will iterate.

In the bash script I was using before this, I simply had as a puppet variable

hosts => "host1,host2"

which I provided to the bash script as

HOSTS=<%= hosts %>

obviously this won't quite work for ruby - I need it in the format

hosts = ["host1","host2"]

since

p hosts

and

puts my_array.inspect

provide the output

["host1","host2"]

I was hoping to use one of those. Unfortunately, I cannot for the life of me figure out how to make that work. I've tried each of the following:

<% p hosts %>
<% puts hosts.inspect %>

I found somewhere where they indicated I'd need to put "function_" in front of function calls...that doesn't seem to work. I've settled on an iterative model:

[<% hosts.each do |host| -%>"<%=host%>",<% end -%>]

this works, giving me

["host1","host2",]

but the trailing comma feels sloppy. the whole thing feels sloppy. Does anyone have a better way? Or is what I've done the best option?

like image 763
Hitch Avatar asked Aug 10 '12 22:08

Hitch


2 Answers

I've solved (Puppet v3.0.1) this way:

{
    "your_key1": {
        "your_key2": [<% puppet_var.join('", "').each do |val| %>"<%= val %>"<% end -%>]
    }
}

If $puppet_var is an array like [ "a", "b" ] output should look something like:

{
    "your_key1": {
        "your_key2": ["a", "b"]
    }
}
like image 79
Alexander Fortin Avatar answered Nov 03 '22 02:11

Alexander Fortin


Ruby allows the use of the %w shorcut between brackets to initialize arrays. This will do:

hosts = %w{<%= hosts.join(' ') %>}
like image 29
Jose Fernandez Avatar answered Nov 03 '22 02:11

Jose Fernandez