0

I have an action in a controller where I want to generate a batch of 10 consecutive days for each request.

I keep track of where we are in the batch cycle by passing a variable page, for each batch.

The cycle of batches should start with today.

How can I express this in the simplest way?

Right now I have the following mess, which doesn't even work (each batch, except for the first one, start one day too early):

@page_number = (params[:page_number] || 0).to_i + 1
today        = Date.today
batch_amount = 10
first_day_of_current_batch = today + (batch_amount * (@page_number - 1))
days         = first_day_of_current_batch..(first_day_of_current_batch + batch_amount)
4

2 回答 2

1

我建议您的页面编号从开始0(即第 #0 页,第一个,从 开始Date.today)。然后,您可以使用以下内容:

@page_number = (params[:page_number] || 0).to_i
batch_amount = 10
first = (@page_number * batch_amount).days.from_now.to_date
last  = ((@page_number + 1) * batch_amount - 1).days.from_now.to_date
days = (first..last).to_a

允许您将to_date范围指定为连续天的范围,to_a并将范围转换ArrayDate对象,每天一个。

于 2013-10-27T18:02:05.657 回答
1

由于我不完全了解您的所有要求,因此我将做出一些假设:

  • 1以,开头的页面nil假定为1
  • 今天是 10 月 27 日,假设批次大小为 10 且页码为 1,批次应为Sun, 27 Oct 2013..Wed, 05 Nov 2013
  • 今天是 10 月 27 日,假设批次大小为 10 且页码为 2,批次应为Sun, 06 Oct 2013..Wed, 15 Nov 2013

由于您在那里有一个相当复杂的逻辑,因此将其提取到单独的对象中是明智的。它被认为是一种常见且良好的做法,因为它将您的代码和测试解耦。自定义类:

# app/services/batch_of_days.rb
class Services::BatchOfDays
  class << self
    def create(page_nr = 1, batch_size = 10, start_from = Date.today)
      new(page_nr.to_i, batch_size, start_from).create
    end
  end

  def initialize(page_nr, batch_size, start_from)
    @page_nr    = page_nr
    @batch_size = batch_size
    @start_from = start_from
  end

  def create
    first_day..last_day
  end

private
  def first_day
    @first_day ||= @start_from + ( @page_nr - 1 ) * @batch_size
  end

  def last_day
    first_day + @batch_size - 1
  end
end

用法:

irb(main):262:0> BatchOfDays.create
# => Sun, 27 Oct 2013..Tue, 05 Nov 2013
irb(main):262:0> BatchOfDays.create(1)
# => Sun, 27 Oct 2013..Tue, 05 Nov 2013
irb(main):263:0> BatchOfDays.create(2)
# => Wed, 06 Nov 2013..Fri, 15 Nov 2013
irb(main):264:0> BatchOfDays.create(3)
# => Sat, 16 Nov 2013..Mon, 25 Nov 2013
于 2013-10-27T21:26:17.127 回答