Skip to content

Instantly share code, notes, and snippets.

@joost
Forked from toobulkeh/deploy.rb
Last active October 10, 2018 09:12
Show Gist options
  • Save joost/9343156 to your computer and use it in GitHub Desktop.
Save joost/9343156 to your computer and use it in GitHub Desktop.
Capistrano 3 rails console tasks
# encoding: UTF-8
# Place in config/deploy.rb
# See: https://gist.github.com/joost/9343156
# Adapted to work with rbenv
namespace :rails do
desc "Open the rails console on primary app server"
task :console do
on roles(:app), primary: true do
rails_env = fetch(:stage)
execute_interactively "#{bundle_cmd} #{current_path}/script/rails console #{rails_env}"
end
end
desc "Open the rails dbconsole on primary db server"
task :dbconsole do
on roles(:db), primary: true do
rails_env = fetch(:stage)
execute_interactively "#{bundle_cmd} #{current_path}/script/rails dbconsole #{rails_env}"
end
end
def execute_interactively(command)
user = fetch(:user)
port = fetch(:port) || 22
cmd = "ssh -l #{user} #{host} -p #{port} -t 'cd #{deploy_to}/current && #{command}'"
info "Connecting to #{host}"
exec cmd
end
def bundle_cmd
if fetch(:rbenv_ruby)
# FIXME: Is there a better way to do this? How does "execute :bundle" work?
"RBENV_ROOT=#{fetch(:rbenv_path)} RBENV_VERSION=#{fetch(:rbenv_ruby)} #{File.join(fetch(:rbenv_path), '/bin/rbenv')} exec bundle exec"
else
"ruby "
end
end
end
@joost
Copy link
Author

joost commented Mar 4, 2014

@phstc
Copy link

phstc commented Jun 16, 2014

The problem is when you have more than one server in the servers list, this task ^^^ will try to open the console in all of them. :/

A possible solution:

namespace :rails do
  desc 'Open a rails console `cap [staging] rails:console [server_index default: 0]`'
  task :console do
    on roles(:app) do |server|
      server_index = ARGV[2].to_i

      return if server != roles(:app)[server_index]

      puts "Opening a console on: #{host}...."

      cmd = "ssh #{server.user}@#{host} -t 'cd #{fetch(:deploy_to)}/current && RAILS_ENV=#{fetch(:rails_env)} bundle exec rails console'"

      puts cmd

      exec cmd
    end
  end
end
cap [staging] rails:console   # connect to the first server
cap [staging] rails:console 1 # connect to the second server

@ktaragorn
Copy link

For bundle_cmd u can use map(:bundle) instead

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