Search code examples
rubyruby-on-rails-3rescue

Ruby/Rails break out of method inside loop


I have two methods I use to sync categories to a 3rd party service. The first method loops through everything and the second actually exports each category. If there is a failure, how do I break out of the loop completely?

def export_all
  Category.find_each do |c|
    export_category(c)
  end
end

def export_category(c)
  begin
    sync_category(c)
  rescue Exception => e
    # break out of `export_all` loop
  end
end

Solution

  • You have a couple of options for breaking out of a loop. Most simply, you can use break or return in your looping code.

    In the context of your example above, it might be easier, if possible within the larger context of your application, to do the following:

    def export_all
      Category.find_each do |c|
        begin 
          export_category(c)
        rescue SpecificErrorIsBetterThanGenericExceptionIfPossible => e
          break
        end
      end
    end
    
    def export_category(c)
      sync_category(c)
    end
    

    It appears from your question that you want the loop in your export_all method to break when an exception is encountered. In such a case, I prefer my break/error handling code at that level.