2014-09-30 106 views
1

我有两种方法可以将类别同步到第三方服务。第一种方法遍历所有内容,第二种方法实际导出每个类别。如果出现故障,我如何彻底摆脱循环?Ruby/Rails跳出循环内的方法

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 

回答

1

你有几个选项可以打破循环。最简单的,您可以在循环代码中使用breakreturn

在您的例子以上的情况下,可能你的应用程序的大背景下更容易,如果可能的话,要做到以下几点:

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 

这似乎从你的问题,你要在循环你的export_all方法在遇到异常时中断。在这种情况下,我更喜欢我的破解/错误处理代码。