【问题标题】:infinite loop in a rake task iterating over an ActiveSupport date range在 ActiveSupport 日期范围内迭代的 rake 任务中的无限循环
【发布时间】:2012-07-23 14:25:42
【问题描述】:

我的 rake 任务陷入无限循环时遇到问题。到目前为止,我已经能够将问题隔离为一段将日期范围转换为数组的代码。即使我直接调用它:

(1.month.ago.beginning_of_month..1.month.ago.end_of_month).to_a.each {|d| p d}

任务在迭代相同的元素时永远挂起:

"2012-06-01 00:40:41 UTC"
"2012-06-01 00:40:41 UTC"
"2012-06-01 00:40:41 UTC"
"2012-06-01 00:40:41 UTC"
"2012-05-31 20:40:41 UTC"
"2012-05-31 20:40:41 UTC"
"2012-06-01 00:40:42 UTC"
"2012-06-01 00:40:42 UTC"
"2012-06-01 00:40:42 UTC"
"2012-06-01 00:40:42 UTC"
"2012-05-31 20:40:42 UTC"
"2012-05-31 20:40:42 UTC"
...

如果我改用这个

(Date.new(2012,6,1)..Date.new(2012,6,30)).to_a.each {|d| p d}

一切正常,因此必须专门针对日期/时间使用 ActiveSupport 扩展。有没有其他人看过这个?

这发生在带有 Rails 3.1 和 Ruby 1.9.3 的 Windows 机器上的开发环境中,如果这很重要的话。

【问题讨论】:

    标签: ruby-on-rails rake activesupport


    【解决方案1】:

    您正在创建一个月的 Time 范围,增量为 1 秒,条目约为 250 万:

    (1.month.ago.beginning_of_month..1.month.ago.end_of_month)
    # => Fri, 01 Jun 2012 00:00:00 CEST +02:00..Sat, 30 Jun 2012 23:59:59 CEST +02:00
    1.month.ago.beginning_of_month.succ
    # => Fri, 01 Jun 2012 00:00:01 CEST +02:00
    

    要创建Date 范围,请使用:

    (1.month.ago.beginning_of_month.to_date..1.month.ago.end_of_month.to_date)
    # => Fri, 01 Jun 2012..Sat, 30 Jun 2012
    1.month.ago.beginning_of_month.to_date.succ
    # => Sat, 02 Jun 2012
    

    【讨论】:

    • 是的,我刚刚发现我所采用的无限循环实际上是一个月内每秒迭代一次的循环......将边界从 ActiveSupport::TimeWithZone 转换为 Dates 有效.
    【解决方案2】:

    使用to_dateActiveSupport::TimeWithZone 转换为Date

    (1.month.ago.beginning_of_month.to_date..1.month.ago.end_of_month.to_date).
      each do |day| 
        p day
      end
    

    这将在过去一个月的几天内迭代。

    看来问题在于在ActiveSupport::TimeWithZone 上使用succ 方法,这会引发Time#succ is obsolete 警告。

    【讨论】:

    • 这不是真正的警告(由于某种原因,我只有在 Rails 控制台中运行此代码时才会看到它们,而不是从 rake 中运行),而是具有无数次迭代的循环才是罪魁祸首,正如 Stefan 指出的那样.无论如何,+1 以获得可接受的解决方案。
    猜你喜欢
    • 2013-03-20
    • 2014-11-15
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-07
    相关资源
    最近更新 更多