1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rails の lib 自動読み込み

Posted at

railsで自作moduleを作成したときにエラーに出くわした

uninitialized constant Hoge::Fuga::Piyo (NameError)

以下の設定でlibディレクトリ以下のファイルはすべて勝手に読み込まれると思っていた

config/application.rb
module App
  class Application < Rails::Application
    ...
    config.autoload_lib(ignore: %w[assets tasks])
    ...
  end
end

libディレクトリ構造

ファイルの置き場所はmoduleの定義に合わせないと読み込まれない

lib/hoge/fuga/piyo.rb
module Hoge
  module Fuga
    module Piyo
      def custome_method
        ...
      end
    end
  end
end

上記の場合は lib/hoge/fuga/piyo.rb にファイルを配置する

classの場合も同様

lib/hoge/fuga/piyo.rb
module Hoge
  module Fuga
    class Piyo
      def custome_method
        ...
      end
    end
  end
end

上記の場合も lib/hoge/fuga/piyo.rb にファイルを配置する

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?