How do I return early from a rake task?

2019-01-16 05:19发布

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

标签: ruby rake
7条回答
何必那么认真
2楼-- · 2019-01-16 05:54

Return with an Error

If you're returning with an error (i.e. an exit code of 1) you'll want to use abort, which also takes an optional string param that will get outputted on exit:

task :check do
  errors = get_errors

  abort( "There are #{errors.count} errors!" ) if errors.any?

  # Do remaining checks...
end

On the command line:

$ rake check && echo "All good"
#=> There are 2 errors!

Return with Success

If you're returning without an error (i.e. an exit code of 0) you'll want to use exit, which does not take a string param.

task :check do
  errors = get_errors

  exit if errors.empty?

  # Process errors...
end

On the command line:

$ rake check && echo "All good"
#=> All good

This is important if you're using this in a cron job or something that needs to do something afterwards based on whether the rake task was successful or not.

查看更多
登录 后发表回答