Vargrantfile-Ruby-文件意外结束

时间:2019-02-16 10:00:07

标签: ruby vagrant vagrantfile

我是红宝石的新手。我试图修改现有的Vargrantfile,它是ruby语法。 我有以下

def has_program(program)
  ENV['PATH'].split(File::PATH_SEPARATOR).any? do |directory|
    File.executable?(File.join(directory, program.to_s))
  end
end 

is_exist = has_program("some-command")
puts is_exist
$my_script = %{
if is_exist == false
  if ! some-command status; then
    #Do some staff
  fi
end
# do some staff
}

Vagrant.configure("2") do |config|

   node.vm.provision "shell", inline: $my_script
end

然后在运行vagrant up --provision时出现错误消息

syntax error: unexpected end of file

能否让我知道我在做什么错误?

关于, -M-

1 个答案:

答案 0 :(得分:1)

这是一种语法错误,但在您的Ruby代码中并非如此。这是您从Ruby脚本执行的shell代码中未完成的语句。

如果您未关闭某个区块,则可能会发生这种情况。解析器希望找到其结尾,但遇到脚本结尾。

让我们看看您正在执行shell命令的部分

$my_script = %{
if is_exist == false
  if ! some-command status; then
    #Do some staff
  fi
end
# do some staff
}

现在,让我们剥离周围的Ruby部分。分配$my_script =仍然是Ruby代码。花括号中的部分是% notation中的字符串文字,稍后您将使用Vagrant的inline作为shell脚本执行...。但是,看来您在切换结束之前要切换回Ruby语法字符串文字。

解释器解析为shell脚本的部分是这部分:

if is_exist == false
  if ! some-command status; then
    #Do some staff
  fi
end
# do some staff

请注意,整个外部if表达式都使用Ruby的if语法。这不是有效的shell命令,因此会出错。

我不确定您所使用的表达式的语义是什么,但是您需要将其转换为外壳if或将其移到要使用{{1 }} 选项。从侧面说,内部逻辑似乎很奇怪。如果inline返回false,则您正在呼叫some-command。但这是一个单独的故事:)