Railsのautoload_paths

autoload_paths について、きちんと調べてみました。

とは言うものの、Autoloading and Reloading Constants — Ruby on Rails Guides にほぼ知りたいことは書かれていたので、重要なポイントを抜粋しておきます。訳は適当です。

autoload_paths の デフォルト

require 'erb'

Ruby looks for the file in the directories listed in $LOAD_PATH. That is, Ruby iterates over all its directories and for each one of them checks whether they have a file called "erb.rb", or "erb.so", or "erb.o", or "erb.dll". If it finds any of them, the interpreter loads it and ends the search.

Ruby は $LOAD_PATH に書かれたディレクトリを探します。つまり、Ruby はそれぞれのディレクトリに "erb.rb", "erb.so", "erb.o" または "erb.dll" があるか1つずつ調べていきます。もし、見つかったら、ファイルをロードし、そこで探すのを終了します。

Alright, Rails has a collection of directories similar to $LOAD_PATH in which to look up post.rb. That collection is called autoload_paths and by default it contains:

  • All subdirectories of app in the application and engines. For example, app/controllers. They do not need to be the default ones, any custom directories like app/workers belong automatically to autoload_paths.

  • Any existing second level directories called app/*/concerns in the application and engines.

  • The directory test/mailers/previews.

Rails は $LOAD_PATH と同様のディレクトリコレクションを持っています。これは autoload_paths と呼ばれており、デフォルトで以下を含みます。

  • app のサブディレクトリ全て。 app/workers のようなカスタムディレクトリも自動的に autoload_paths に含まれる。
  • app/*/concerns ディレクトリ
  • test/mailers/previews

autoload_pathsの設定

Also, this collection is configurable via config.autoload_paths. For example, lib was in the list years ago, but no longer is. An application can opt-in by adding this to config/application.rb:

config.autoload_paths によって設定することができます。 lib を追加するなら config/application.rb で以下のようにすればよいです。

config.autoload_paths << "#{Rails.root}/lib"

autoload_pathsの確認

$ bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'