capistrano-plugins/capistrano-delayed-job — pull request #3 by jcypret (2014-12-28 22:08:26+00:00)
Title: Fix rbenv-capistrano compatibility

When using capistrano-rbenv, the unicorn_init file is generated incorrectly. This is caused by the way capistrano-rbenv prefixes `SSHKit::Command` with environmental variables. This results in the call to `SSHKit::Command.new(:bundle, :exec …` to generate `RBENV_ROOT=/opt/rbenv RBENV_VERSION=2.2.0 /opt/rbenv/bin/rbenv exec bundle exec`.

This is caused by the following code in capistrano-rbenv:

SSHKit.config.default_env.merge!({ rbenv_root: fetch(:rbenv_path), rbenv_version: fetch(:rbenv_ruby) })

The `bundle_delayed_job` helper currently uses the SSHKit::Command to access delayed_job:

SSHKit::Command.new(:bundle, :exec, "#{bin_dir}/delayed_job", args).to_command

This generates the following when capistrano-rbenv is present:

RBENV_ROOT=/opt/rbenv RBENV_VERSION=2.2.0 /opt/rbenv/bin/rbenv exec bundle exec bin/delayed_job $op -n 1

SSHKit tries to encapsulate the the entire command so it adds parenthesis. The problem is that the environmental variables and the nice command are added to the command string outside of the `SSHKit::Command`. You end up with the following:

cd $APP_ROOT && HOME=/home/$AS_USER RAILS_ENV=staging nice -n 15 ( RBENV_ROOT=/opt/rbenv RBENV_VERSION=2.2.0 /opt/rbenv/bin/rbenv exec bundle exec bin/delayed_job $op -n 1 )

This will not work for a couple of reasons. The parenthesis are added because environmental variables are being added by SSHKit. Removing the parenthesis does not work either, because then you are passing an environmental variable to the nice command, which is expecting an executable.

By moving nice and the environmental variables into the `SSHKit::Command `, the command is correctly generated:

CMD="cd $APP_ROOT && ( RBENV_ROOT=/opt/rbenv RBENV_VERSION=2.2.0 /usr/bin/env HOME=/home/$AS_USER RAILS_ENV=staging nice -n 15 bundle exec bin/delayed_job $op -n 1 )"

This will also correct any other potential issues where environmental variables are set with SSHKit.