Reputation: 893
Suppose I have two files, parent.yaml.erb and and child.yaml.erb and I would like to include the contents of child.yaml.erb inside of parent.yaml.erb and calculate it in context of parent.yaml.erb. Example:
parent.yaml.erb:
name: parent
first:
second:
third: something
<%= ERB.new(File.read('child.yaml.erb')).result(binding) %>
child.yaml.erb:
<% if some_condition %>
a:
b:
c: <%= 2+2 %>
<% end %>
I expect this result:
expected_result.yaml:
name: parent
first:
second:
third: something
a:
b:
c: 4
What I get instead is:
result.yaml:
name: parent
first:
second:
third: something
*[whitespace ends here]*
a:
b:
c: 4
Using trim_mode option from documentation doesn't help.
How do I achieve expected result with correct indentation?
ruby 2.6.4p104 (2019-08-28 revision 67798) [x86_64-linux]
Upvotes: 0
Views: 1481
Reputation: 15472
You could do it this way.
name: parent
first:
second:
third: something
<%- content = ERB.new(File.read("child.yaml.erb"), nil, "-").result().gsub(/^/," ") -%>
<%= content -%>
<% if some_condition -%>
a:
b:
c: <%= 2+2 %>
<% end -%>
nil
and "-"
as 2nd and 3rd arguments to ERB.new()
. <$-
and -%>
.gsub
to indent by 4 spaces.Of course, as noted in comments, it could be better to read the YAML data into memory as a hash, although I do realise you lose a lot of control of the output that way.
Upvotes: 1