如何使用主动支持核心分机日期和时间

how to use active support core ext date and time

active_support/core_ext/date_and_time/calculations 有什么用? DateTimeDateTime分别有/date/time/date_time。但是 /date_and_time 有什么用呢?

我试图要求它而不是 date_time,然后我得到了文件中定义的方法的 NoMethodError。

那些模块 date_and_time 在那里是因为它们是所有 DateTimeDateTime 核心扩展中包含的模块。这些模块使用相同的方法扩展了那些 classes。因此,它们被分组在日期 时间下,因为您在所有 classes.

中获得相同的新方法

因此,它们是模块,旨在作为扩展包含在内。您不能单独要求它们并期待新功能,除非您打算使用它们通过 include.

扩展 class 功能

这里有一个直接来自 Rails 来源的示例,说明它是如何使用的(在本例中取自 core_ext/date/calculations):

require "active_support/core_ext/date_and_time/calculations"

class Date
  include DateAndTime::Calculations
  ...
end

您可以look at the source yourself, or check out the docs添加方法。

例如,在 DateTime 中使用该扩展名,您现在可以:

Time.now.last_year
Date.today.last_year

同样的方法适用于两个 classes。