Help us understand the problem. What is going on with this article?

capistrano3でrails_envを指定してコマンドを実行する

More than 5 years have passed since last update.

capistrano3でRAILS_ENVを指定してrakeを実行するのに手間取ったので、ここで共有します。

問題 下記の方法ではrails_envが呼べない

deploy.rb
namespace :deploy do
  task :reset_db do
    on roles(:app) do
      execute "cd #{deploy_to}/current && bundle exec rake db:seed RAILS_ENV=#{rails_env}"
    end
  end
end

上記の方法だと下記のようなrails_envが定義されていないことを示すエラーが出ます。

cap aborted!
undefined local variable or method 'rails_env' for #<SSHKit::Backend::Netssh:0x007f1cd58044b0>

解法1 fetchを通して呼ぶ

deploy.rb
namespace :deploy do
  task :reset_db do
    on roles(:app) do
      execute "cd #{deploy_to}/current && bundle exec rake db:seed RAILS_ENV=#{fetch :rails_env}"
    end
  end
end

こうして書くと、文字列内でrails_envを呼べます

解法2 withを使う

下の例ではcd #{deploy_to}/currentも簡素化するためにwithinを使っています

deploy.rb
namespace :deploy do
  task :reset_db do
    on roles(:app) do
      within release_path do
        with rails_env: fetch(:rails_env) do
          execute :rake, "db:migrate:reset"
        end
      end
    end
  end
end

こうして書くと指定したRAILS_ENVrakeを実行できます

参考
http://blog.huangzhimin.com/2013/11/02/upgrade-to-capistrano3/

asukiaaa
おいしい食事と心地良い睡眠を楽しむために生きています。
https://asukiaaa.blogspot.com
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした