是否有在 Vagrantfiles 中引用变量的样式指南?

Is There A Style Guide For Quoting Variables In Vagrantfiles?

当我查看 Vagrant 文档时 https://www.vagrantup.com/docs/networking/forwarded_ports.html 它给出了一个这样的例子:

Vagrant.configure("2") do |config|
  config.vm.network "forwarded_port", guest: 2003, host: 12003, protocol: "tcp"
  config.vm.network "forwarded_port", guest: 2003, host: 12003, protocol: "udp"
end

然而,以下似乎也有效:

单引号

Vagrant.configure("2") do |config|
  config.vm.network 'forwarded_port', guest: 2003, host: 12003, protocol: "tcp"
  config.vm.network 'forwarded_port', guest: 2003, host: 12003, protocol: "udp"
end

冒号前缀

Vagrant.configure("2") do |config|
  config.vm.network :forwarded_port, guest: 2003, host: 12003, protocol: "tcp"
  config.vm.network :forwarded_port, guest: 2003, host: 12003, protocol: "udp"
end

这些语法有什么区别?双引号只应该在你有变量时使用 like in puppet?

什么是冒号前缀语法?这是令人困惑的,因为该行的其余关键字都带有冒号后缀。

是否有 Vagranfiles 的风格指南?

Vagrantfile 是一个 ruby 脚本,因此它遵守 ruby 规则。

使用双引号的主要优点之一是当您需要 string interpolation

免责声明:以下是自以为是(只是我对此的看法)。但所有的风格指南也是如此。不要陷入对这背后原因的深思熟虑,只要做出你的选择并尽量保持一致。

Vagrantfiles 有样式指南吗?

很快:Use this style guide

长答案:似乎没有任何官方的 Vagrant 风格指南,但由于它是 Ruby 编程语言,我们可以看看官方的 Ruby 风格指南......哦,等等,Ruby 实际上也有 none!这个可能是最受欢迎的,所以坚持下去:

rubocop-hq/ruby-style-guide

我应该使用什么:单引号 ('word')、双引号 ("word") 或符号 (:word)?

简而言之:使用双引号。

长答案:风格指南在单引号和双引号问题上是矛盾的:it offers you choice A and B,所以坚持使用 Vagrant 文档:

  • 默认使用双引号:

    node.vm.provision "shell", inline: "echo hello from node #{i}"

  • 如果双引号是字符串的一部分,请使用单引号。这个snippet from Vagrant documentation is consistent with style guide:

    config.winssh.export_command_template = '$env:%ENV_KEY%="%ENV_VALUE%"'

什么是冒号前缀语法?

很快:冒号标记为 symbol (see Ruby documentation)。

这个答案再扩展一点:What is the colon operator in Ruby?

什么时候应该在 Vagrantfile 中使用 symbols

不久:(几乎)从不

长答案:坚持使用双引号以保持一致性,除非您在 Vagrant 解析 Vagrantfile 时确实遇到了可变性或性能问题。 Ruby 中有关符号和字符串的性能和可变性的更多信息:The Difference Between Ruby Symbols and Strings.