You can invoke a rake task from another rake task.
Here’s how:
examples.rake
123456789101112131415
namespace:examplesdodesc"Inner task."task:inner_task=>:environmentdo# Some code that accomplishes a task.enddesc"Outer task."task:outer_taskdo# Some code.Rake::Task['examples:inner_task'].execute#Execute innter task.# Some other code.endend
Now when you execute rake examples:outer_task, you will execute the inner task in whatever context you placed it.
Using this contruction allows you to break down unweildy tasks into smaller ones, which perhaps you’ll want to reuse in different contexts elsewhere.
Here’s a toy examples that actually works:
toys.rake
123456789101112131415
namespace:toysdodesc"Inner task: Square the value."task:squaredo@value*=@valueenddesc"Outer task: Initialize the value and square thrice."task:square_three_timesdo@value=23.times{Rake::Task['toys:square'].execute}puts"The value is #{@value}."endend
Running this in the shell, we get:
1234567
$ rake toys:square_three_times --trace
** Invoke toys:square_three_times (first_time)** Execute toys:square_three_times
** Execute toys:square
** Execute toys:square
** Execute toys:square
The value is 256.
And yes, I know you’re thinking it now: rake tasks can call themselves quite happily.
You can also invoke rake tasks from within ActiveRecord migrations.
This can come in handy when you want to initialize a bunch of data immeidately after altering the database schema.