[英]Ruby on Rails - How to generate a YAML file with a key that starts with a dot?
I would like generate on Ruby on Rails a YAML file with a key that start with a dot ( . before_script_template
), like我想在 Ruby on Rails 上生成一个 YAML 文件,其中的键以点(
. before_script_template
)开头,例如
.before_script_template:
before_script:
- gem install bundler
but I am generating a string like ".before_script_template":
但我正在生成一个类似
".before_script_template":
".before_script_template":
before_script:
- gem install bundler
This is my code in Ruby to generate .yml
file:这是我在 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
How can I generate a key like .before_script_template:
instead of ".before_script_template":
?我怎样才能生成像
.before_script_template:
而不是".before_script_template":
这样的密钥?
Both YAML docs are equivalent.两个 YAML 文档是等效的。 One is simply using quotes to clarify the key.
一种是简单地使用引号来阐明关键。
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
This has nothing to do with YAML specifically as both .before_script_template
and ".before_script_template"
are valid tags in YAML.这与 YAML 无关,因为
.before_script_template
和".before_script_template"
都是 YAML 中的有效标签。
This has to do with the implementation determined by the parser/emitter ( Psych
in this case).这与解析器/发射器(在本例中为
Psych
)确定的实现有关。
Specifically this is shown in Psych::Visitors::YAMLTree
class in the method visit_String
具体来说,这显示在方法
visit_String
的Psych::Visitors::YAMLTree
类中
As far as the quoting style goes this code boils down to:就引用风格而言,这段代码归结为:
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
In this case DOUBLE_QUOTED
is utilized because:在这种情况下,使用
DOUBLE_QUOTED
是因为:
".before_script_template" =~ /^[^[:word:]][^"]*$/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.