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
Differencebetween 'Range#Include' and 'Range#Cover'
How to Convert a Ruby Hash to Xml
Looping Through an Array with Step
Ruby on Rails Rake Assets:Precompile Error
Rails on Windows - Install Issue
Google Maps, Ruby on Rails, Zoom Level with One Marker
Portable Ruby on Rails Environment
Variable Scope and Order of Parsing VS. Operations: Assignment in an "If"
Rails, Postgresql, and History Triggers
Run Rspec Tasks in a Specific Order
How to Capture Values in Command Line and Add to Recipe
What's the Difference Between Colon ":" and Fat Arrow "=>"
Return Index of All Occurrences of a Character in a String in Ruby
Problems Installing Ruby on Mountain Lion - Ruby 1.9.3 Wont' Compile
Rails Gem Rails3-Jquery-Autocomplete How to Scope by User
Ruby 1.9 + Sinatra Incompatible Character Encodings: Ascii-8Bit and Utf-8