无法自动加载常量 AuthenticateFromToken,需要 ./app/api/authenticate_from_token.rb 来定义它

Unable to autoload constant AuthenticateFromToken, expected ./app/api/authenticate_from_token.rb to define it

当我开始编写我的第一个 rails API 时,我将所有 API 代码放在 app/core/api 目录下并将其添加到自动加载路径

config.autoload_paths += %W[
  #{config.root}/lib
  #{config.root}/app/core]

之后我决定将 API 类 移动到 app 文件夹。现在,当我 运行 我的测试时,我收到了这个错误

 Failure/Error: authenticate = API::AuthenticateFromToken.(params[:auth_token])

 LoadError:
   Unable to autoload constant AuthenticateFromToken, expected ./app/api/authenticate_from_token.rb to define it

从令牌进行身份验证如下所示:

module API
  class AuthenticateFromToken

    prepend SimpleCommand

    def initialize(auth_token)
      @auth_token = auth_token
    end

    def call
      # authenticate code
    end
  end
end

在将 api 目录从 app/core 移动到 app 之前,我没有遇到任何自动加载问题。这段代码出了什么问题?

如果class在API模块下,应该保存在api文件夹下。

问题是 Rails 默认自动加载 app 文件夹下的所有文件夹,因此您需要将其放入 app/api/api/authenticate_from_token.rb

更多信息:https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths-and-eager-load-paths