使用Rails环境进行“私有”Rake任务

时间:2021-10-02 01:14:50

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:

我知道我可以使用以下内容来调用子任务列表,并让每个子任务都使用我项目的Rails环境:

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. 是否有任何方法:main_task传递:环境,以便我不必在每个子任务中明确地将它放入?

  3. 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.
  4. 有没有办法让子任务被视为“私人”?也就是说,我不希望它们被单独显式调用。他们只会执行:main_task。基本上我需要从一个数据库(SQLServer)中读取数据并填充另一个数据库(MySQL - Rails项目的数据库),但我希望将“读取”任务与“填充”任务分开以获得良好的可读性。

1 个解决方案

#1


6  

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).

没有“私人”任务,但是你可以通过不在它们上面放置desc线来阻止它们被rake -T列出。如果直接调用异常(检测父进程或某些异常),可以通过抛出异常来手动强制执行它们。

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.

但是,您可能有更好的时间将代码放在共享方法或类中,而不是直接公开为rake任务。

#1


6  

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).

没有“私人”任务,但是你可以通过不在它们上面放置desc线来阻止它们被rake -T列出。如果直接调用异常(检测父进程或某些异常),可以通过抛出异常来手动强制执行它们。

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.

但是,您可能有更好的时间将代码放在共享方法或类中,而不是直接公开为rake任务。