我有一个文件,如下所示
#app/services/account/authenticate/base.rb
module Account
module Authenticate
AuthenticateError = Class.new(StandardError)
class Base < ::Account::Base
def self.call(*attrs)
raise NotImplementedError
end
end
end
end现在,当我从rails c运行代码时,我得到了一个错误
> ::Account::Authenticate::AuthenticateError
=> NameError (uninitialized constant Account::Authenticate::AuthenticateError)
> ::Account::Authenticate.constants
=> [:Base, :ViaToken]所以rails看不到AuthenticateError类。但是当我要从这个文件夹创建一个嵌套类时,比如
=> Account::Authenticate::ViaToken
> ::Account::Authenticate.constants
=> [:Base, :AuthenticateError, :ViaToken]AuthenticateError类现在可见
> ::Account::Authenticate::AuthenticateError
=> Account::Authenticate::AuthenticateError这个问题的解决方案是创建一个单独的文件authenticate_error.rb,它将从一开始就可以工作,但这种解决方案对我来说并不理想。是否有预加载所有类或smth的解决方案?
(Ruby 2.6和Rails 6.0.0.rc2)
发布于 2020-03-27 13:11:17
在将Rails 6.0.2应用程序部署到Ubuntu 18.04服务器上时,我遇到了同样的问题。
无法加载应用程序:Zeitwerk::Unable错误:需要文件/home/deploy/myapp/app/models/concerns/designation.rb来定义常量指定,但没有这样做
我发现问题出在zeitwerk上。Zeitwerk是Rails6中使用的新代码加载器引擎,它将取代旧的经典引擎,成为所有Rails 6+项目的新默认引擎。Zeitwerk提供了代码自动加载、即时加载和重载的功能。
这里是我如何解决它的
导航到项目上的config/application.rb文件。
在应用程序模块中添加以下行,以切换到classic模式以进行自动加载:
config.autoloader = :classic下面是一个例子:
module MyApp
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 6.0
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
config.autoloader = :classic
end
end您可以在本文中阅读有关zeitwerk的更多信息:Understanding Zeitwerk in Rails 6
就这样。
我希望这对有帮助
发布于 2021-09-15 03:39:04
将Rails应用程序从5.2升级到6.0,同时也遇到了Zeitwerk的问题!
如果您希望继续使用当前使用的自动加载模式,请避免使用Zeitwerk,然后将该行添加到application.rb文件(@PromisePreston answer和Rails doc)中。
config.autoloader = :classic如果你想升级到Zeitwerk,那么可以使用的命令是bin/rails zeitwerk:check (来自这个guide article)。
我们遇到的最接近这个特定问题的场景是,我们在子文件夹中有一个文件,如下所示:
#presenters/submission_files/base.rb
module Presenters
module SubmissionFiles
class Base < Showtime::Presenter
def method_call
#code_here
end
end
end
end删除额外的模块将具有:
#presenters/submission_files/base.rb
module Presenters
class SubmissionFiles::Base < Showtime::Presenter
def method_call
#code_here
end
end
end然后,当在应用程序的其他ruby文件中调用该方法时,请使用:Presenters::SubmissionFiles::Base.method_call
发布于 2021-07-15 10:30:13
Zeitwerk自动加载某些预期的文件夹,其中包括应用程序/模型、应用程序/控制器、应用程序/助手等。
我创建了一个文件夹app/helpers并将我的services文件夹移到其中。
就这样!
https://stackoverflow.com/questions/57277351
复制相似问题