Hitch
Hitch

Reputation: 51

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?

Upvotes: 5

Views: 8551

Answers (3)

Jose Fernandez
Jose Fernandez

Reputation: 2761

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

hosts = %w{<%= hosts.join(' ') %>}

Upvotes: 3

Alexander Fortin
Alexander Fortin

Reputation: 129

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"]
    }
}

Upvotes: 5

numbers1311407
numbers1311407

Reputation: 34072

Use to_json;

hosts.to_json
=> "[\"host1\",\"host2\"]"

Upvotes: 0

Related Questions