为什么 Rails6+ 默认开始在 config/environments/* 中添加 activesupport require ?

Nik*_*hev 4 ruby-on-rails activesupport ruby-on-rails-6 zeitwerk

我的 Rails 版本升级有点晚了。让我惊讶的是 Rails 生成的 config/environment/* 文件中需要一堆 active_support 。

它们是做什么用的?这和Rails6中引入的Zeitwerk有什么关系吗?我不记得它们出现在旧版本的 Rails 中。

ag ^require config/environments
config/environments/development.rb
1:require "active_support/core_ext/integer/time"

config/environments/test.rb
1:require "active_support/core_ext/integer/time"

config/environments/production.rb
1:require "active_support/core_ext/integer/time"
Run Code Online (Sandbox Code Playgroud)

重现步骤:

rails new myapp

cat Gemfile  | grep "^gem 'rails'"
gem 'rails', '~> 6.1.3', '>= 6.1.3.2'
Run Code Online (Sandbox Code Playgroud)

我试图在 Rails/rails CHANGELOG 和一些 git blaiming 中找到此更新,但这没有帮助。

Sco*_*man 5

在每个环境文件的更下方,使用 require 语句加载的代码(或者在生产文件的情况下在注释中引用)。从默认值开始development.rb

\n
# Enable/disable caching. By default caching is disabled.\n# Run rails dev:cache to toggle caching.\nif Rails.root.join(\'tmp/caching-dev.txt\').exist?\n  config.cache_store = :memory_store\n  config.public_file_server.headers = {\n    \'Cache-Control\' => "public, max-age=#{2.days.to_i}" # <- NOTE THIS LINE\n  }\nelse\n  config.action_controller.perform_caching = false\n\n  config.cache_store = :null_store\nend\n
Run Code Online (Sandbox Code Playgroud)\n

require语句增加了对表达式的支持,例如2.days.to_i-core_ext/integer/time加载一些函数,但也需要core_ext/numeric/time.

\n

因此,该require声明是一个好的 Ruby 公民,并确保保证加载其代码所依赖的 Rails 特定部分,以便能够正确解析该行。

\n

我不知道为什么以前不需要它(这可能是与 Zeitwerk 相关的问题,正如您所建议的,这是 Rails 6+ 的一部分,我还不太熟悉)。

\n

但归根结底,如果在评估此文件之前加载了整个 Rails 堆栈,则 require 不会产生任何额外效果 \xe2\x80\x93 ,如果没有,此文件将加载什么它需要,然后 Rails 的其余部分将根据需要加载。

\n