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

EJA*_*JAg 1 ruby datetime ruby-on-rails activesupport

active_support/core_ext/date_and_time/calculations为了什么?分别有/date/time/date_timeDateTimeDateTime。但到底是/date_and_time为了什么?

我尝试使用 require 它而不是date_time,然后我得到了文件中定义的方法的 NoMethodError 。

Cas*_*per 5

Those modules date_and_time are there because they are modules that are included by all of the Date, Time and DateTime core extensions. Those modules extend those classes with the same methods. Hence they are grouped under Date and Time, because you get the same new methods across all classes.

So, they are modules, meant to be included as extensions. You cannot require them separately and expect new functionality, unless you are meaning to use them to extend class functionality through include.

Here's an example directly from the Rails source on how it's used (taken from core_ext/date/calculations in this case):

require "active_support/core_ext/date_and_time/calculations"

class Date
  include DateAndTime::Calculations
  ...
end
Run Code Online (Sandbox Code Playgroud)

You can look at the source yourself, or check out the docs for the added methods.

For example, with that extension in both Date and Time, you can now do:

Time.now.last_year
Date.today.last_year
Run Code Online (Sandbox Code Playgroud)

Same method is available, for both classes.