Search code examples
ruby-on-railsrubyrakeraise

Ruby: How do I stop execution and print a string in a loop?


I am writing a rake task. The thing is that I want to stop execution of the task when if keeper.has_trevance_info? && candidate.has_trevance_info? is true. I just want it to print Another record already has that info! in the log and stop the task. How would I do that? Would it be raise or throw?

  billing_infos.each do |candidate|
    unless keeper.nil?
      raise "Another record already has that info! Manually compare BillingInfo ##{keeper.id}
             and ##{candidate.id}" if keeper.has_trevance_info? && candidate.has_trevance_info?

    else
      keeper = candidate
    end

  end

Solution

  • You don't want to use exception handling to exit the task. You can use 'abort' or 'exit'.

    So your code would do something like this:

    billing_infos.each do |candidate|
      unless keeper.nil?
        if keeper.has_trevance_info? && candidate.has_trevance_info?
          puts "Another record already has that info! Manually compare BillingInfo ##{keeper.id}"
          exit
        end
      else
        keeper = candidate
      end
    end
    

    Or:

    billing_infos.each do |candidate|
      unless keeper.nil?
        abort("Another record already has that info! Manually compare BillingInfo ##{keeper.id}") if keeper.has_trevance_info? && candidate.has_trevance_info?
      else
        keeper = candidate
      end
    end