Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Mellon Avatar asked Dec 01 '11 14:12

Mellon


People also ask

When would you use a rake task?

Rake allows you to define a list of other tasks that must run before the current task.

How do I run a rake task?

Go to Websites & Domains and click Ruby. After gems installation you can try to run a Rake task by clicking Run rake task. In the opened dialog, you can provide some parameters and click OK - this will be equivalent to running the rake utility with the specified parameters in the command line.


1 Answers

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.

like image 59
David Sulc Avatar answered Sep 22 '22 18:09

David Sulc