【问题标题】:Getting "Unable to autoload constant" .. '"expected app/lib/subfolder/module.rb to define it"获取“无法自动加载常量”..“预期 app/lib/subfolder/module.rb 来定义它”
【发布时间】:2019-12-25 01:15:14
【问题描述】:

我正在尝试加载模块:

 #MainApp/app/lib/game/pieces.rb
  module Pieces
    class Pawn
        def initialize
           puts "I'm a piece!"
        end
     end
  end

在模型中:

 # MainApp/app/models/boardgame.rb
 class Boardgame < ApplicationRecord
   include Game::Pieces
 end

但我得到“无法自动加载常量 Game::Pieces,预期 /home/..MainApp/app/lib/game/pieces.rb 来定义它(LoadError)”

我尝试在 autoload_paths 和 eager_load_paths 中设置文件夹:

 # config/application.rb
 module MainApp
   class Application < Rails::Application
      config.load_defaults 5.2
      config.autoload_paths << Rails.root.join('app/lib/game')
      config.eager_load_paths << Rails.root.join('app/lib/game')
   end
 end

但它仍然不起作用,如果我将模块放在 app/lib 中,它会完美加载它,问题只出现在子文件夹中。

【问题讨论】:

  • 您在MainApp/app/lib/game/pieces.rb 中定义了Pieces::Piece,但试图包含Game::Piece。这没有意义,是吗?
  • 您缺少命名约定...
  • 我意识到了,现在:/ 谢谢

标签: ruby-on-rails ruby module


【解决方案1】:

当您包含Game::Pieces 时,您的模块应该如下所示:

module Game
  module Pieces
    # some code here
  end
end

除此之外,在 Ruby 和 Rails 中构建的首选方式是根据您的模块名称命名您的目录,因此您的模块路径宁愿是 lib/game/pieces.rb。 请考虑包含一个模块,而不是一个类

【讨论】:

    【解决方案2】:

    您在模块Pieces 中定义了一个类Piece,但您希望在模块游戏中使用一个类Piece。需要将MainApp/app/lib/game/pieces.rb中的代码改成

      module Game
        class Piece
            def initialize
               puts "I'm a piece!"
            end
         end
      end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-28
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多