【问题标题】:Rails 5.2 autoload is not working in developmentRails 5.2 自动加载在开发中不起作用
【发布时间】:2019-07-25 20:27:56
【问题描述】:

我有一个 Rails 5.2 项目,结构如下:

  • 应用/
  • 应用程序/身份验证
  • app/auth/oauth_controller.rb
  • app/auth/oauth.rb

oauth_controller.rb

require_relative "./oauth.rb"

module Auth
  class OauthController < Infra::BaseController
    include ActionController::Cookies

    def start
      oauth = Auth::OAuth.new(session: session)
      ...
    end

    def callback
      oauth = Auth::OAuth.new(session: session)
      ...
    end
  end
end

oauth.rb

module Auth
  class OAuth
    ...
  end
end

要让Auth::Oauth 工作,我必须要求oauth.rb 文件,所以我认为急切加载或自动加载不起作用。但是,即使使用require(),当我更改文件时,我再次收到此错误,我必须一次又一次地重新启动服务器。

未初始化的常量 Auth::OAuth

这是我的application.rb

config.middleware.use ActionDispatch::Cookies
config.api_only = false
config.eager_load_paths += %W(#{config.root}/app)
config.time_zone = 'Etc/UTC'
config.reload_controllers = !Rails.env.production?

development.rb 没有改变。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    这是因为 rails 期望的命名约定。 Rails 期望文件名 o_auth.rbOAuth 匹配。您需要添加感染以支持OAuthoauth.rb

    config/initializers/inflections.rb添加

    ActiveSupport::Inflector.inflections(:en) do |inflect|
      inflect.acronym 'OAuth'
    end
    

    您需要将文件名更改为o_auth.rb

    在这两种情况下,您都不需要require_relative "./oauth.rb"

    此外,如果这是一个控制器,它应该位于 app/controllers/auth/o_auth 中,而不是直接位于 app/

    【讨论】:

      【解决方案2】:

      除其他答案外,app 下的文件夹不被解释为模块,仅用于组织。所以app/auth/oauth.rb应该是这样的

      class Oauth
      

      不是

      module Auth
        class Oauth
      

      【讨论】:

      • 我不相信这是一个模型,所以它不会继承自 ApplicationRecord
      • @theartofbeing - 足够公平,尽管与我的观点根本无关。
      • 嗨@jvillian,Rails 允许我们拥有灵活的结构。不是您必须遵循初始实施的强制性事情。感谢您抽出宝贵的时间来回答!
      猜你喜欢
      • 2016-08-01
      • 2023-03-27
      • 1970-01-01
      • 2022-08-10
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多