Ruby/Rails 如何在日期时间范围内迭代月份?

Qqw*_*qwy 4 ruby iteration datetime ruby-on-rails

我正在尝试根据 Rails 表中的数据构建图表:每个时间片段的销售产品数量。

因为图表应该能够显示最后一小时(以 1 分钟为步长)、最后一天(以 1 小时为步长)、上周(以 1 天为步长)、最后一个月(以 1 天为步长) )等,我试图通过迭代一系列 DateTime 对象来减少代码重复:

# To prevent code-duplication, iterate over different time ranges.
times = {
    :hour=>{newer_than: 1.hour.ago, timestep: :minute},
    :day=>{newer_than: 1.day.ago, timestep: :hour},
    :week=>{newer_than: 1.week.ago, , timestep: :day},
    :month=>{newer_than: 1.week.ago, , timestep: :day}
}


products = Product.all

# Create symbols `:beginning_of_minute`, `:beginning_of_hour`, etc. These are used to group products and timestamps by.
times.each do|name, t| 
  t[:beginning_of] = ("beginning_of_" << t[:timestep].to_s).to_sym 
end 

graphs = times.map do |name, t|
   graphpoints = {}
   seconds_in_a_day = 1.day.to_f
   step_ratio = 1.send(t[:timestep]).ago.to_f / seconds_in_a_day
   time_enum = 1.send(t[:timestep]).ago.to_datetime.step(DateTime.now, step_ratio)
   time_enum.each do |timestep|
       graphpoints[time_moment.send(timehash[:beginning_of]).to_datetime] = []
   end

   # Load all products that are visible in this graph size
   visible_products = products.select {|p| p.created_at >= t.newer_than}
   # Group them per graph point
   grouped_products = visible_products.group_by {|item| item.created_at.send(timehash[:beginning_of]).to_datetime}

   graphpoints.merge!(grouped_products)

   {
      points: graphpoints,
      labels: graphpoints.keys
   }
end
Run Code Online (Sandbox Code Playgroud)

此代码适用于所有具有恒定大小的时间间隔(小时、天、周)。然而,在几个月内,它使用 30 天的 step_ratio:1.month / 1.day == 30。显然,月份的天数并不是恒定的。在我的脚本中,这会导致一个月可能被“跳过”,因此从图表中消失。

如何解决这个问题呢?如何迭代几个月,同时记住几个月中不同的天数?

fan*_*eqi 5

如果您必须在巨大的数组中选择月份,只需将范围设置在两个 Date:class 之间即可。

(1.year.ago.to_date..DateTime.now.to_date)).select{|date| date.day==1}.each do |date|
  p date
end
Run Code Online (Sandbox Code Playgroud)