Eri*_*c K 12 ruby ruby-on-rails
我正在Ruby on Rails中创建一个库式系统,我试图想出一种计算过期天数的方法,同时排除借用项目时的周末.现在我只计算"dayslate"作为截止日期和项目实际返回日期之间的差异,但我想排除周末,因为项目只能在工作日返回.
这是我第一次使用Ruby和Rails的真实体验,所以如果我遗漏了一些明显的东西,我很抱歉.感谢您提供的任何帮助.
这是我对"返回"功能的代码:
def return
@product = Product.find(params[:id])
today = Date.today
dayslate = today - @product.due_date
if @product.due_date >= today
@product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil
@product.save!
flash[:notice] = "Okay, it's checked in!"
redirect_to(products_url)
else
@product.borrower = @product.check_out = @product.due_date = @product.extended_checkout = nil
@product.save!
flash[:notice] = "Checked in, but it was #{dayslate} days late!"
redirect_to(products_url)
end
end
Run Code Online (Sandbox Code Playgroud)
Ben*_*ini 24
这是一段代码,用于查找日期范围对象中的工作日数
require 'date'
# Calculate the number of weekdays since 14 days ago
p ( (Date.today - 14)..(Date.today) ).select {|d| (1..5).include?(d.wday) }.size
Run Code Online (Sandbox Code Playgroud)
这就是我在你的情况下使用它的方式.
class Product
def days_late
weekdays_in_date_range( self.due_date..(Date.today) )
end
protected
def weekdays_in_date_range(range)
# You could modify the select block to also check for holidays
range.select { |d| (1..5).include?(d.wday) }.size
end
end
Run Code Online (Sandbox Code Playgroud)