29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

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

Last updated at Posted at 2014-03-02

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/

29
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?