簡體   English   中英

廚師Ruby - 可以在模板的變量中循環嗎?

[英]Chef Ruby — are Loops within the variables for template possible?

我已經花了很多時間試圖弄清楚如何做到這一點,我也調查了但是我還沒找到合適的方法......?

基本上我正在嘗試做類似以下的事情:

types = ['type1','type2']
classes = ['class1','class2']

classes.each do |class|
    types.each do |type|

        template "/files/filename.txt" do
          source "source_file.erb"
          owner "root"
          group "root"
          mode "0440"
          variables({
            :pri_areas => node['area']['#{type}']['#{class}'],
            :rev_areas => node['area']['#{type}']['#{class}']
        })
        end

    end
end

顯然我已經定義了所有已經定義的屬性,所以從那個方面看起來一切都很好..我還是無法設法得到一個帶有變量的數組的循環? 也許另一種不同的做法

任何想法/幫助?

非常感謝。

您的代碼有一些問題需要在正常工作之前修復。

起初, class是Ruby中的保留關鍵字,因此不能用作變量名。 你應該使用另一個,例如klass

其次, class (或klass )以及type都已經在你的循環中的字符串。 因此,您不需要嘗試字符串插值。 你可以直接使用這個:

variables({
  :pri_areas => node['area'][type][klass],
  :rev_areas => node['area'][type][klass]
})

你的字符串插值不起作用的原因是ruby知道兩種不同的字符串文字:帶有"和帶有'的字符串。不同之處在於用'不允許字符串插值並且通常不解釋任何內容然后作為文字書寫字符串以外的其他東西。只有在字符串分隔的" ,你可以執行字符串插值,如"#{foo}"並使用轉義序列,如\\n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM