代码之家  ›  专栏  ›  技术社区  ›  EJAg

如何使用活动支持核心扩展日期和时间

  •  1
  • EJAg  · 技术社区  · 7 年前

    是什么 active_support/core_ext/date_and_time/calculations 为了什么?有 /date , /time /date_time 对于 Date , Time DateTime ,分别是。但是什么是 /date_and_time 为了什么?

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

    1 回复  |  直到 7 年前
        1
  •  4
  •   Casper    7 年前

    那些模块 date_and_time 是因为它们是所有 Date , Time DateTime 核心延伸。这些模块用相同的方法扩展这些类。因此,它们在日期下分组 时间,因为在所有类中都有相同的新方法。

    所以,它们是模块,应该作为扩展包含。除非您打算使用它们来扩展类功能,否则不能单独要求它们并期望新功能。 include .

    下面是一个直接从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 check out the docs 对于添加的方法。

    例如,在 日期 时间 ,现在可以执行以下操作:

    Time.now.last_year
    Date.today.last_year
    

    两个类都有相同的方法。