将 gem 升级到 Rails 7 后,我看到很多未定义常量错误。
例如:
应用程序/模型/my_gem/api/irr_item.rb
module MyGem
module Api
class IrrItem < MyGem::Api::ApplicationRecord
在我的班级中将
IRR
大写时,它解决了问题:
module MyGem
module Api
class IRRItem < MyGem::Api::ApplicationRecord
或者另一种情况:
应用程序/约束/graphiql_route_constraint.rb
class GraphiqlRouteConstraint
在我的班级中将
QL
大写时,它解决了问题:
class GraphiQLRouteConstraint
我通过大写解决了所有问题,但我不明白为什么。是不是因为我在某个地方有一个名为
IRR
的模块,现在它需要一直大写?
在经典中,自动加载器的输入是缺失常量的名称“IrrItem”。自动加载器在“irr_item”下划线,并在文件系统中查找该文件。
Zeitwerk 则相反。自动加载器的输入是文件名,并假设
"irr_item".camelize
是其中定义的常量。正如@max所说,看起来应用程序已经定义了首字母缩略词。
我想如果在所有实例中都使用缩写词就好了。但要快速解除阻止,您可以对这些特殊情况进行硬编码:
# config/initializers/zeitwerk.rb
# IRR and GraphQL are defined as acronyms, but we have
# some classes whose names do not take them into account.
# If they get ever renamed, please remove this configuration.
main = Rails.autoloaders.main
main.inflector.inflect(
"irr_item" => "IrrItem",
"graphiql_route_constraint" => "GraphiqlRouteConstraint"
)
请查看这些文档以了解更多详细信息。
另请参阅指南 Zeitwerk HOWTO 经典,了解迁移中可能出现的更多内容。