Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Private" Rake tasks with the Rails environment

I know I can have the following to call a list of sub-tasks and have each one utilize the Rails environment of my project:

task :main_task => [:sub_task1, :sub_task2] do
end

task :sub_task1 => :environment do
  Model1.some_class_method
end

task :sub_task2 => :environment do
  Model2.some_class_method
end


My questions are

  1. Is there any way in :main_task to pass the :environment so that I don't have to explicitly put it in each sub-task?
  2. Is there any way to make the sub-tasks be considered "private"? That is, I don't want them to be explicitly called individually. They would only ever execute from :main_task. Basically I need to read data out of one database (SQLServer) and populate another (MySQL - the Rails project's db), but I want to keep the "read" task separate from the "populate" task for good readability.
like image 543
istrasci Avatar asked Feb 04 '13 18:02

istrasci


People also ask

What is environment Rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.

When would you use a Rake task?

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

Where is Rake task defined?

In any Rails application you can see which rake tasks are available - either by running rake -AT (or rake --all --tasks) to see all tasks, or rake -T (or rake --tasks ) to see all tasks with descriptions.

What is Rake clean?

Now running rake clean will remove your files, as well as the predefined set of temporary files if any have bean created. Follow this answer to receive notifications.


1 Answers

You can list the :environment task once in the parent task before the other two to have it listed only once.

task :main_task => [:environment, :sub_task1, :sub_task2] do
end

There are no "private" tasks, however you can keep them from being listed by rake -T by not putting a desc line above them. You could enforce them manually by throwing an exception if they are called directly (detecting something the parent does, or some such).

However, you would probably have a better time putting the code in a shared method or class which is not directly exposed as a rake task.

like image 59
Daniel Evans Avatar answered Oct 16 '22 22:10

Daniel Evans