Skip to content

Instantly share code, notes, and snippets.

@toobulkeh
Forked from benedikt/rails.rb
Created January 2, 2014 02:42
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save toobulkeh/8214198 to your computer and use it in GitHub Desktop.
Save toobulkeh/8214198 to your computer and use it in GitHub Desktop.
Updated for Capistrano 3.
# encoding: UTF-8
# Place in config/deploy.rb
namespace :rails do
desc "Open the rails console on each of the remote servers"
task :console do
on roles(:app) do |host| #does it for each host, bad.
rails_env = fetch(:stage)
execute_interactively "ruby #{current_path}/script/rails console #{rails_env}"
end
end
desc "Open the rails dbconsole on each of the remote servers"
task :dbconsole do
on roles(:db) do |host| #does it for each host, bad.
rails_env = fetch(:stage)
execute_interactively "ruby #{current_path}/script/rails dbconsole #{rails_env}"
end
end
def execute_interactively(command)
user = fetch(:user)
port = fetch(:port) || 22
exec "ssh -l #{user} #{host} -p #{port} -t 'cd #{deploy_to}/current && #{command}'"
end
end
@DmytroLukianov
Copy link

DmytroLukianov commented Jul 27, 2017

For rbenv:

namespace :rails do
  desc "Open the rails console"
  task :console do
    on roles(:app) do
      rails_env = fetch(:rails_env, 'production')
      execute_interactively "$HOME/.rbenv/bin/rbenv exec bundle exec rails console #{rails_env}"
    end
  end

  desc "Open the rails dbconsole"
  task :dbconsole do
    on roles(:app) do
      rails_env = fetch(:rails_env, 'production')
      execute_interactively "$HOME/.rbenv/bin/rbenv exec bundle exec rails dbconsole #{rails_env}"
    end
  end

  def execute_interactively(command)
    user = fetch(:user)
    port = fetch(:port) || 22
    exec "ssh -l #{user} #{host} -p #{port} -t 'cd #{deploy_to}/current && #{command}'"
  end
end

@rannyeribaptist
Copy link

In case anyone still have issues with rbenv and @DmytroLukianov solution, I tuned it a bit and it worked for me:

namespace :rails do
  desc 'Start a rails console'
  # Usage: cap production rails:console
  task :console do
    on roles(:app) do
      exec "ssh #{host.user}@#{host.hostname} -p #{host.port || 22} -t 'cd #{current_path} && $HOME/.rbenv/bin/rbenv exec bundle exec rails console'"
    end
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment