Ruby templating using YAML datasources
require 'ruyml'
require 'yaml'
content = YAML.load(File.read("file.yml"))
r = Ruyml::Data.new(content)
r.render_file("template.erb", "output.txt")
# Or retrieve it as string and do something with it
parsed = r.render_string('template.erb')
Given a yaml file :
alert:
message: 'hello world !'
And an erb file :
message = "<%= alert.message.capitalize %>"
Running :
ruyml -d alert.yaml -t template.erb
Gives the following output :
message = "Hello world !"
You can refer to multiple YAML datasources in a template and render it using :
ruyml -d data1.yaml,data2.yaml -t template.erb
When iterating over an item which is not a leaf of the YAML file, you can access
methods of the Hash class directly. In case a propertie has the same name than
the method you are trying to use, simply use the <method>!
form.
For instance :
object:
each:
- attr1: val1
- attr2: val2
- attr3: val3
Object dump :
<%= object.each %>
Object attributes:
<% object.each! do |p, items| -%>
<% items.each do |attr, val| -%>
Attribute <%= attr %> has value <%= val %>
<% end -%>
<% end -%>