簡體   English   中英

Ruby on Rails - 如何使用以點開頭的鍵生成 YAML 文件?

[英]Ruby on Rails - How to generate a YAML file with a key that starts with a dot?

我想在 Ruby on Rails 上生成一個 YAML 文件,其中的鍵以點( . before_script_template )開頭,例如

.before_script_template:
  before_script:
    - gem install bundler

但我正在生成一個類似".before_script_template":

".before_script_template":
  before_script:
  - gem install bundler

這是我在 Ruby 中生成.yml文件的代碼:

  pipeline_file = { 
                    ".before_script_template" => {"before_script" => ["gem install bundler"]}
                  }

  File.open("./my_project/folder/.gitlab-ci-template.yml", "r+") do |f|
    f.write(pipeline_file.to_yaml.gsub(/^---$/, ""))
  end

我怎樣才能生成像.before_script_template:而不是".before_script_template":這樣的密鑰?

兩個 YAML 文檔是等效的。 一種是簡單地使用引號來闡明關鍵。

require 'yaml'

# {".before_script_template"=>{"before_script"=>["gem install bundler"]}}
p YAML.load(<<-END)
".before_script_template":
  before_script:
  - gem install bundler
END

# {".before_script_template"=>{"before_script"=>["gem install bundler"]}}
p YAML.load(<<-END)
.before_script_template:
  before_script:
  - gem install bundler
END

這與 YAML 無關,因為.before_script_template".before_script_template"都是 YAML 中的有效標簽。

這與解析器/發射器(在本例中為Psych )確定的實現有關。

具體來說,這顯示在方法visit_StringPsych::Visitors::YAMLTree類中

就引用風格而言,這段代碼歸結為:

 PLAIN         = 1
 SINGLE_QUOTED = 2
 DOUBLE_QUOTED = 3
 LITERAL       = 4
 FOLDED        = 5

def quoting_style(o)
  style = PLAIN
  if o.encoding == Encoding::ASCII_8BIT && !o.ascii_only?
    style = LITERAL
  elsif o =~ /\n(?!\Z)/  
    style = LITERAL
  elsif o == '<<'
    style = SINGLE_QUOTED
  elsif o == 'y' || o == 'n'
    style = DOUBLE_QUOTED
  elsif @line_width && o.length > @line_width
    style = FOLDED
  elsif o =~ /^[^[:word:]][^"]*$/
    style = DOUBLE_QUOTED
 # elsif not String === @ss.tokenize(o) or /\A0[0-7]*[89]/ =~ o
 # commented out so you can see it but this question is not about the ScalarScanner
 # (https://github.com/ruby/psych/blob/v5.0.0/lib/psych/scalar_scanner.rb)
 #   style = SINGLE_QUOTED
  end
  style
end 

quoting_style("before_script") #=> 1
quoting_style(".before_script_template") #=> 3

在這種情況下,使用DOUBLE_QUOTED是因為:

".before_script_template" =~ /^[^[:word:]][^"]*$/

例子

暫無
暫無

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

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