Sunday, 15 August 2010

How to apply a mapping to a value in a Puppet/Ruby ERB template? -



How to apply a mapping to a value in a Puppet/Ruby ERB template? -

i'm writing erb template (for puppet module) gets passed hash this:

{"stuff" => {"foo"=>"aaa", "bar"=>"ccc"}, "other" => {"foo"=>"bbb", "bar"=>"ddd"}}

and i'm iterating on in templates producing rows of text:

<% @my_data.each_pair |k, v| -%> <%= k %> <%= v["foo"] %>:<%= v["bar"] %> <% end -%>

now i'd apply mapping "foo" info sec hash i'll pass template. in pseudocode:

mappings = {"aaa" => "something", "bbb" => "somethingelse"} <% @my_data.each_pair |k, v| -%> <%= k %> <%= translate_somehow(v["foo"], mappings) %>:<%= v["bar"] %> <% end -%>

...in order "something" whenever value "aaa", , on. expect original value if there no corresponding key in "mappings".

doing kind of thing in puppet's language possible (by extending ruby code) think more appropriate in erb template, don't know how , not knowing ruby isn't helping me - tried google without much success.

i'm looking code accomplish in erb function or pointers relevant documentation rtfm pleasure.

edit: future readers, here's digitalross' reply translated erb illustration above:

<% @my_data.each_pair |k, v| -%> <%= k %> <%= mappings[v["foo"]] || v["foo"] %>:<%= v["bar"] %> <% end -%>

with erb stuff removed clarity, want do. (the p() function prints argument. can seek in irb.)

@my_data.each |k, v| f, b = v['foo'], v['bar'] p(mappings[f] || f) p(mappings[b] || b) end

ruby erb puppet

No comments:

Post a Comment