我正在尝试用一些逻辑写入厨师食谱中的erb模板。我有以下,我认为会有效。目前属性为零,但它并没有像我想象的那样跳过整个区块。如何获得顶部语句以使模板阅读器跳过整个块?
<% unless node['base']['logstash-forwarder']['nginx'].nil? %>
<%= "{" %>
<%= "\"paths\": [" %>
<% node['base']['logstash-forwarder']['nginx'].each do |path| %>
<% unless path.equal? node['base']['logstash-forwarder']['nginx'].last %>
<%= "\"#{path}\"," %>
<% end %>
<% end %>
<%= "\"#{node['base']['logstash-forwarder']['nginx'].last}\"" %>
<%= " ]," %>
<%= "\"fields\": { \"type\": \"nginx-access\" }" %>
<%= "}" %>
<% end %>
答案 0 :(得分:2)
上面的确切代码与ERB中的预期完全一致,请参阅:
[122] pry(main)> e = ERB.new <<'EOI'
[122] pry(main)* <% unless node['base']['logstash-forwarder']['nginx'].nil? %>
[122] pry(main)* <%= "{" %>
[122] pry(main)* <%= "\"paths\": [" %>
[122] pry(main)* <% node['base']['logstash-forwarder']['nginx'].each do |path| %>
[122] pry(main)* <% unless path.equal? node['base']['logstash-forwarder']['nginx'].last %>
[122] pry(main)* <%= "\"#{path}\"," %>
[122] pry(main)* <% end %>
[122] pry(main)* <% end %>
[122] pry(main)* <%= "\"#{node['base']['logstash-forwarder']['nginx'].last}\"" %>
[122] pry(main)* <%= " ]," %>
[122] pry(main)* <%= "\"fields\": { \"type\": \"nginx-access\" }" %>
[122] pry(main)* <%= "}" %>
[122] pry(main)* <% end %>
[122] pry(main)* EOI
=> #<ERB:0x007fe74bb35ff8
@encoding=#<Encoding:UTF-8>,
@filename=nil,
@lineno=0,
@safe_level=nil,
@src=
"#coding:UTF-8\n_erbout = ''; _erbout.concat \" \"; unless node['base']['logstash-forwarder']['nginx'].nil? ; _erbout.concat \"\\n \"\n; _erbout.concat(( \"{\" ).to_s); _erbout.concat \"\\n \"\n; _erbout.concat(( \"\\\"paths\\\": [\" ).to_s); _erbout.concat \"\\n \"\n; node['base']['logstash-forwarder']['nginx'].each do |path| ; _erbout.concat \"\\n \"\n; unless path.equal? node['base']['logstash-forwarder']['nginx'].last ; _erbout.concat \"\\n \"\n; _erbout.concat(( \"\\\"\#{path}\\\",\" ).to_s); _erbout.concat \"\\n \"\n; end ; _erbout.concat \"\\n \"\n; end ; _erbout.concat \"\\n \"\n; _erbout.concat(( \"\\\"\#{node['base']['logstash-forwarder']['nginx'].last}\\\"\" ).to_s); _erbout.concat \"\\n \"\n; _erbout.concat(( \" ],\" ).to_s); _erbout.concat \"\\n \"\n; _erbout.concat(( \"\\\"fields\\\": { \\\"type\\\": \\\"nginx-access\\\" }\" ).to_s); _erbout.concat \"\\n \"\n; _erbout.concat(( \"}\" ).to_s); _erbout.concat \"\\n \"\n; end ; _erbout.concat \"\\n\"\n; _erbout.force_encoding(__ENCODING__)">
[123] pry(main)> node = { 'base' => { 'logstash-forwarder' => {}}}
=> {"base"=>{"logstash-forwarder"=>{}}}
[124] pry(main)> path = nil
=> nil
[125] pry(main)> e.result binding
=> " \n"
[126] pry(main)>
所以问题是,厨师做了一些奇怪的事情(似乎不太可能),或者你的node
不像你想象的那样nil?
。
在行之间进行阅读,特别是在.each
和.last
来电时,您的node['base']['logstash-forwarder']['nginx']
实际上可能不是nil
,而是[]
?
如果是,请将.nil?
支票更改为.empty?