Capistrano Ruby:重构重用的字符串值

Capistrano Ruby: Refactoring Reused String Values

我的 deploy.rb 文件中有几个任务在我的主题文件夹中执行。

我目前定义如下:

namespace :deploy do
   desc 'NPM Build Production'
   task :npm_build_production do
      on roles(:app) do
          within "#{release_path}/web/app/themes/example" do
             execute :npm, "install --silent --no-progress"
             execute :npm, "run build:production"
          end;
      end
   end
end

before 'deploy:updated', 'deploy:npm_build_production'

此实现一切正常,但由于我在多个实例中使用此路径,因此我想将其提取到一个符号或变量中。我是 Ruby 的新手并且 运行 遇到了一些问题。

我试过使用下面的代码,但由于某种原因,在我的任务中执行时路径最终是错误的。

set :theme_path, -> { "#{release_path}/web/app/themes/example" }

这些变量是在不同的实施阶段设置的。例如 release_path 变量未在设置变量部分中定义。将您的变量移动到您的执行块以进行任务分配,它将起作用。例如,这个片段将起作用

namespace :deploy do desc 'NPM Build Production' task :npm_build_production do on roles(:app) do theme_path = "#{release_path}/web/app/themes/example" within theme_path do execute :npm, "install --silent --no-progress" execute :npm, "run build:production" end; end end end 您还可以在设置 fetch(:varible_name) 等其他变量时使用这种方式获取一些变量,但我不确定 release_path 是否可行,因为它是一个作用域变量

这里是你如何用一个函数来做到这一点

      def theme_path(release_path)
          "#{release_path}/web/app/themes/example" 
      end

只需使用您的 release_path 变量调用此函数,您就可以在任意位置获得主题路径。在您的部署逻辑中。