10

In Capistrano using the Multi-stage extension I have two environments: prod and testing.

I need a few variables in testing.rb that are not needed in prod.rb and I want some of my tasks to be able to check if the variable is defined and use it if it is, but ignore it if it is not set.

So, in testing.rb I would have something like:

set :foo, 'bar'

prod.rb wouldn't have any reference to :foo since it doesn't need it. In one of my tasks, I would like to do something like:

if defined?(foo)
  # do something with foo
else
  # do something without foo
end

But I keep getting the error:

undefined local variable or method 'foo'

Is there a way to test for undefined global variables in the task? Or do I have to do something like:

set :foo, ''

In all my environments that don't need the :foo variable?

Jaymon
  • 5,363
  • 3
  • 34
  • 34

1 Answers1

16

Try using exists?(:foo) instead of defined?(foo), as recommended in the Capistrano docs.

zetetic
  • 47,184
  • 10
  • 111
  • 119
  • 1
    To expand on this a little: the defined? method takes a symbol (:foo) rather than a variable (foo). The set method doesn't actually create proper ruby variables, it just holds the values in an internal store. That is why you need to use fetch(:foo) to get the value. – Jamie Penney Feb 08 '11 at 00:19
  • That worked, thanks. I'm pretty unfamiliar with Ruby and I figured there was an easy solution like this but Google had failed me and I missed it in the documentation. I figured the variables were being set differently, so they needed to be checked differently but not knowing to use exists? I was completely stumped. Thanks again. – Jaymon Feb 08 '11 at 00:43
  • This is crazy! I was trying with defined? – Senthil Kumaran Aug 22 '12 at 02:30
  • @JamiePenney Defined works with the actual variable - http://i.imgur.com/SW1MPI4.png if you give it a symbol it will *always* say that it's a valid "expression" ruby-doc is down atm so here is a related question from SO: http://stackoverflow.com/questions/288715/checking-if-a-variable-is-defined-in-ruby – Jamie Cook Jun 10 '13 at 23:00
  • 1
    Hi, would you know the equivalent for Capistrano 3? – kaizenCoder May 05 '14 at 02:59