tags:

views:

260

answers:

1

I have a rake task where I do some checks at the beginning, if one of the checks fails I would like to return early from the rake task, I don't want to execute any of the remaining code.

I thought the solution would be to place a return where I wanted to return from the code but I get the following error

unexpected return
+8  A: 

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.

Simone Carletti
I like the second one best, too. The more I use rake, the more I like to keep non-trivial code outside of the task definition. Not a 100% firm rule, but seems to be a good guideline to work to.
Mike Woodhouse
I absolutely agree. Also, methods are much more easier to test.
Simone Carletti
The second solution is nicer. In your first solution, I would prefer to use break instead of next to get out of the block... Should work too, shouldn't it?
severin
@severin Yes, it should. I agree, break makes more sense.
Simone Carletti
I've tried with `break` and I've got this error: rake aborted!break from proc-closure(See full trace by running task with --trace)
J. Pablo Fernández