How to Return Early from a Rake Task

How do I return early from a rake task?

A Rake task is basically a block. A block, except lambdas, doesn't support return but you can skip to the next statement using next which in a rake task has the same effect of using return in a method.

task :foo do
puts "printed"
next
puts "never printed"
end

Or you can move the code in a method and use return in the method.

task :foo do
do_something
end

def do_something
puts "startd"
return
puts "end"
end

I prefer the second choice.

Exit from one of a series of Rake tasks and continue with the next

Try using "next" from within your Rake task to jump to the next task if your check method returns nil.

You can use a conditional inside your "check" function to return the value if it exists, or to return nil if the value is nil. Then, if check returns nil, you can use next (not exit) to skip to the next task.

task :main do
Rake::Task['first'].execute(value: 'Hello, Rake world!')
Rake::Task['second'].execute
end

task :first do |_t, args|
value = args[:value]
next if check(value).nil?
puts 'the value is: ' + value
end

task :second do
puts 'the second task'
end

def check(value)
if value.nil?
return nil
else
return value
end
end

Using "next" inside the function definition will not work. You can only skip to the next rake task from inside the current rake task

Call a Rake task repeatedly

rake is OSS, btw.

Rake::Task#invoke checks that the task was not previously invoked and early returns if it was. I do not know much about rake, but resetting this instance variable should do the trick.

Rake::Task["db:work"].tap do |task|
task.invoke(0)
task.instance_variable_set(:@already_invoked, false)
task.invoke(nil)
end

Can I catch errors and continue to next Rake task?

Rake is just Ruby, so you can use Ruby's error handling feature.

namespace :test do
task :migrate do
begin
Rake::Task['A:migrate'].invoke
rescue => e
log(e)
end
Rake::Task['B:migrate'].invoke
end
end

Real-time output of a rake task with popen3

Adding $stdout.sync = true at the beginning of the rake task solved it.



Related Topics



Leave a reply



Submit