[英]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_String
的Psych::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.