JJB Blog

Offering defaults when prompting for user input in Capistrano

I use Capistrano to deploy my Rails projects. I often deploy the same project in several environments– in addition to the production server, we always have a staging server, and sometimes a “data” server where data can be entered before launch. What this means is that I need to modify the server and username variables in deploy.rb whenever I am deploying to a different server, which is a hassle because it brings it out of sync with the version in my Subversion repository. So if I need to commit changes to deploy.rb, I have to do the partial-manual-revert dance: change the variables back to their defaults, commit my other changes, and change the variables back to my custom values. Ugh.

What I would really like is for Capistrano to prompt me for these variables, and also offer defaults with the most common case. Here is my solution:

[ruby]
def prompt_with_default(var, default)
set(var) do
Capistrano::CLI.ui.ask “#{var} [#{default}] : ”
end
set var, default if eval(“#{var.to_s}.empty?”)
end

prompt_with_default(:domain, “example.com”)
prompt_with_default(:user, ENV['USER'])
[/ruby]

Now the user will be prompted for input for each variable. If the user hits enter without entering any text, the default presented in square brackets will be used.

[code]
cap deploy:check
domain [example.com] :
user [john] :
* executing `deploy:check'
..........
[/code]


2 Comments

That’s nice.

Posted by Dr Nic on 18 November 2007 @ 4pm

Very nice! Thanks for the tip

Posted by Dante Regis on 3 March 2008 @ 2pm

Leave a Comment