views:

108

answers:

3

Hello stackoverflow experts,

I got a very strange problem in a task I'm creating with Capistrano. I'm trying to pass a variable from the command line:

>> cap create_dir -s name_of_dir=mydir

task :create_dir do
  printf("#{name_of_dir}")
  if !(exists?(:name_of_dir)) then  
      name_of_dir = Capistrano::CLI.ui.ask("Name of dir to be created.")    
  end   

  full_path = "/home/#{name_of_dir}"
  run "mkdir #{full_path}"

end

The very strange this is that correctly parses the variable when I do printf, but parses as a blank(empty) string in the following command. I really find no explanation for this and I'm sure is not a stuping typo or anything like that?

I'm not expierenced in Ruby like in Java and PHP, I'm affraid that there maybe a strange rule?

Thanks!!

A: 

It looks like in the second line you are checking if the symbol :name_of_dir exists - not the actual value of the variable name_of_dir.

Because you're unlikely to have a filename name_of_dir it will count as not existing... and then name_of_dir (the variable) is overwritten by the Capistrano::CLI.ui.ask command.

Not sure why but that must be killing it somehow.

Try removing the ":" and seeing if that fixes the problem.

Taryn East
A: 

A few suggestions:

  • Avoid using variables with the same name of internal task variables
  • use fetch() instead of dealing with if exits? else then...

Here's the code

>> cap create_dir -s name_of_dir=mydir

task :create_dir do
  printf("#{name_of_dir}")
  directory = fetch(:name_of_dir) { Capistrano::CLI.ui.ask("Name of dir to be created.") }

  full_path = "/home/#{directory}"
  run "mkdir #{full_path}"
end 
Simone Carletti
A: 

In newer versions of capistrano, at least from 2.5.19 which I run now the whole command line argument thing works different now. You call it like this.

cap command argument=value

And the syntax in the code is

ENV.has_key?('argument') and ENV['argument']

That's basically it, but you can look at my blogpost about it for a working example

nasmorn