我正在编写一个涉及日期比较的Ruby脚本.

为了保持它的可读性,我想做像1.day.ago这样的事情.我认为这会很容易,就像将gem 'activesupport'添加到我的gefile中并需要require 'active_support'一样.但这并不管用.

我走得更远:

require "active_support/core_ext/date/calculations"
require "active_support/core_ext/integer/time"
require "active_support/core_ext/time"

但我还不是很清楚:

1.day.ago
#NameError: uninitialized constant ActiveSupport::IsolatedExecutionState
#
#      ::ActiveSupport::IsolatedExecutionState[:time_zone] || zone_default

…我不确定我还需要要求什么.如何在我的普通ruby脚本中使用活动记录的所有日期/时间方法?

推荐答案

你只需要包括ActiveSupport::IsolatedExecutionState例.

# This is not needed because active_support/core_ext/integer/time already requires it
#   require "active_support/core_ext/date/calculations" 
# This is not really needed either as almost all of it will 
# be required by the requirements in active_support/core_ext/integer/time  
#   require "active_support/core_ext/time" 
require "active_support/core_ext/integer/time"
require "active_support/isolated_execution_state.rb"

1.day.ago
#=> 2023-02-20 19:18:49.686473704 +0000

为什么在Active_Support/core_ext/Time/Zones中不需要这样做,我不能说,因为我觉得应该避免这个问题.

如果您真的想要包含全部activesupport,那么就非常接近了,然而,实际的Required语句是require 'active_support/all',该文件的内容很简单:

require "active_support"
require "active_support/time"
require "active_support/core_ext"

Ruby相关问答推荐

这是按引用传递/值传递的误解,导致此方法无法按预期输出吗?

如何修改 Ruby gem

如何关闭 Rails 3.1 上的自动样式表/javascript 生成?

Ruby on Rails:你能把 Ruby 代码放在 YAML 配置文件中吗?

是否有Ruby单行如果 x 则返回?

在 ruby​​ 中调试第三方 gem 的最佳方法

如何从 Gemfile 安装 gem?

Ruby 中的发送方法

C# ?? Ruby 中的运算符?

如何用 Ruby 覆盖 shell 中的打印行?

Ruby - 查看端口是否打开

用零填充数字

RSpec allow/expec vs expect/and_return

是否可以使用 Ruby 读取文件的修改日期?

为什么 __FILE__ 大写而 __dir__ 小写?

为什么这个 Ruby 对象同时具有 to_s 和 inspect 似乎做同样事情的方法?

Ruby 中的动态方法调用

更好的 ruby​​ markdown 解释器?

通过多个分隔符拆分字符串

如何在文件夹及其所有子文件夹中搜索特定类型的文件