Andrew
Andrew

Reputation: 13

Getting "Unable to autoload constant" .. '"expected app/lib/subfolder/module.rb to define it"

I'm trying to load the module:

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

In the model:

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

But i get "Unable to autoload constant Game::Pieces, expected /home/..MainApp/app/lib/game/pieces.rb to define it (LoadError)"

I tried to set the folder in the autoload_paths and 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

but it still doesn't work, if i put the module in app/lib it loads it perfectly, the problem occurs only in a subfolder.

Upvotes: 1

Views: 1110

Answers (2)

Mike Mulev
Mike Mulev

Reputation: 76

When you include Game::Pieces your module should look like that:

module Game
  module Pieces
    # some code here
  end
end

In addition to that, the preferred way of structuring in Ruby and Rails is to name your directory according to your module name, so your module path would rather be lib/game/pieces.rb. And please consider including a module, not a class

Upvotes: 1

mrzasa
mrzasa

Reputation: 23347

You have defined a class Piece in a module Pieces, but you expect a class Piece in a module game. You need to change the code in MainApp/app/lib/game/pieces.rb to

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

Upvotes: 1

Related Questions