Mellon
Mellon

Reputation: 38832

rake task variable

I have two Rake tasks under the same namespace like following:

namespace :db do
  task :first_task => :environment do
         server_name='myserver'
         connect_to(server_name)
  end

  task :second_task => :environment do
          server_name='myserver'
          do_something_with(server_name)
  end
end

As you see, both tasks are under the same namespace and both tasks use server_name='myserver' constant variable.

It really looks ugly to define the server_name variable twice under the same namespace, how can I have one place defining this variable so both tasks can use it?

Upvotes: 21

Views: 15192

Answers (2)

David J.
David J.

Reputation: 32705

I'd like to build on David Sulc's answer, but I recommend using an instance variable instead:

namespace :db do
  @server_name = 'myserver'

  task first_task: :environment do
    connect_to @server_name
  end

  task second_task: :environment do
    do_something_with @server_name
  end
end

The advantage here is that later code can modify @server_name -- something you can't do with a local variable:

namespace :db do
  @server_name = 'server_2'
end

Upvotes: 7

David Sulc
David Sulc

Reputation: 25994

Try this:

namespace :db do
  server_name='myserver'
  task :first_task => :environment do
    connect_to(server_name)
  end

  task :second_task => :environment do
    do_something_with(server_name)
  end
end

Namespaces have access to variables declared before their scope.

Upvotes: 23

Related Questions