命名空间下的 Rake 任务变量 [英] Rake task variable under namespace
问题描述
我今天在我的佣金脚本中看到了一个奇怪的东西.我在不同的命名空间下有两个 Rake 任务,如下所示:
I see a strange thing in my rake script today. I have two Rake tasks under the different namespaces like following:
path = "/home/tomcat/tomcat"
namespace :stage do
path = "/home/tomcat/stage-tomcat"
desc "Deploys a java application to stage tomcat"
task :java_deploy do
puts path # stage:java_deploy should print /home/tomcat/stage-tomcat
end
end
namespace :production do
path = "/home/tomcat/production-tomcat"
desc "Deploys a java application to production tomcat"
task :java_deploy do
puts path # production:java_deploy should print /home/tomcat/production-tomcat
end
end
当我运行时:rake stage:java_deploy
打印
/home/tomcat/production-tomcat
我期待/home/tomcat/stage-tomcat.如果我从 rake 文件中删除第一行 path = "/home/tomcat/tomcat"
,它会按预期工作.
I was expecting /home/tomcat/stage-tomcat. If I remove the very first line path = "/home/tomcat/tomcat"
from the rake file, it works as expected.
知道为什么这个 kolavari 吗?:)
Any idea why this kolavari? :)
提前致谢!!
推荐答案
这不是 Rake 特有的,它只是词法作用域和 Ruby 处理局部变量的方式的结果,在第一次使用时声明它们.
This is not specific to Rake, it is just a consequence of lexical scope and the way Ruby handles local variables, declaring them on first use.
首先给path
赋值:
path = "/home/tomcat/tomcat"
然后创建 stage
命名空间并重新分配变量:
Then you create the stage
namespace and reassign the variable:
path = "/home/tomcat/stage-tomcat"
请注意,此行会在您指定的任何任务中执行,因为它不在任何任务中.
Note that this line is executed whatever task you specify, as it is not in any tasks.
接下来创建 java_deploy
任务,但它尚未运行.这个任务引用了 path
变量,但是当任务被调用时它的值可能已经改变了.
Next you create the java_deploy
task, but it doesn’t get run yet. This task refers to the path
variable, but when the task is called the value of it might have changed.
稍后,在定义 production
命名空间时,此变量会再次重新分配.重要的是,这仍然是相同的变量:
Later, when defining the production
namespace this variable gets reassigned again. Importantly this is still the same variable:
path = "/home/tomcat/production-tomcat"
任务实际运行的时候,引用了path
变量,这个变量的值是最近赋给它的值,也就是/home/tomcat/production-tomcat代码>.
When the task is actually run, it refers to the path
variable and the value of this variable is the latest value assigned to it, which is /home/tomcat/production-tomcat
.
当您删除对 path
的第一个赋值时,该变量不存在于顶层.这意味着当您在每个命名空间定义中分配给 path
时,您在每种情况下都声明了一个新的(和单独的)局部变量.
When you remove the first assignment to path
, then the variable doesn’t exist in the top level. This means that when you assign to path
in each namespace definition you are declaring a new (and separate) local variable in each case.
这篇关于命名空间下的 Rake 任务变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!