4
votes

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 required 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?

1
The classic autoloader used up until Rails 5 is a completely different beast from Zeitwork that was introduced in Rails 6. So the same recommendation do not apply to Rails 5 & 6.max
I would recommend you read the Zeitwork readme if you want to understand how autoloading really works in Rails 6. The guides have not quite caught up and the terminology in Rails is just wrong.max
That's a fair point. I'll specify that I mean the classic autoloader.you786
In a Rails 6 the recommended approach is to switch over to Zeitwork ASAP. The classic autoloader was designed way back in 2004 and relies on const_missing. Ruby has evolved enomously since then and Zeitwork uses Rubys native Module#autoload. Zeitwork does not have many of the known problems of the classic autoloader. medium.com/cedarcode/…max

1 Answers

1
votes

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.