christian christian - 3 months ago 21
Ruby Question

Capistrano Ruby: Refactoring Reused String Values

I have a couple tasks within my deploy.rb file that execute within my theme folder.

I currently define them as follows:

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'


Everything is working correctly with this implementation, but since there are multiple instances where I use this path, I'd like to extract it to a symbol or variable. I am new to Ruby and am running into some issues.

I have tried using the code below, but for some reason the path ends up being wrong when executed in my tasks.

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

Answer

These variables are set on different stages of implementation. for example the release_path variable is not defined in the setting variables section. Move your variable to your execution block for tasking and it will work . for example this snipped will work

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 also you will be able to fetch some variables using this way while setting other variables like fetch(:varible_name) but I am not sure it is feasible for the release_path since it is a scoped variable

here is how you could do it with a function

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

just call this function with your release_path variable and you will have the themepath wherever you want. inside your deployment logic.

Comments