Reputation: 3550
In the past, Rails developers who had files in the lib/
directory were told to add the lib directory to the autoload paths, by adding a line like this to the config/application.rb
:
config.autoload_paths << "lib"
However, the latest Rails guides say that this is now discouraged:
... using autoload_paths on its own in the past (before Rails 5) developers might configure autoload_paths to add in extra locations (e.g.
lib
which used to be an autoload path list years ago, but no longer is). However this is now discouraged for most purposes, as it is likely to lead to production-only errors. It is possible to add new locations to both config.eager_load_paths and config.autoload_paths but use at your own risk.
(emphasis mine)
So instead we are asked to require lib/
files. From the Rails guides:
Of course, using require in autoloaded files to load ordinary 3rd party libraries is fine, and Rails is able to distinguish their constants, they are not marked as autoloaded.
However, this means that changes in those require
d files won't be noticed and served in the next request. So in order to get that to happen for lib/
files, we must add them to the autoload_paths
... which is discouraged above.
So what is the appropriate way to include lib
files in your app, with automatic detection of changes in Rails 5, or Rails 6 with the classic autoloader enabled?
Upvotes: 4
Views: 3771
Reputation: 191
As per this discussion Rails 5: Load lib files in production you should put your libs under app/lib
. Or not. There are different opinions about "appropriate" way.
Upvotes: 1