Why use /app/lib instead of /lib in Rails?
Asked Answered
H

2

14

In the sidekiq documentation, there is this quote about preferring to use /app/lib instead of /lib in Rails projects related to autoloading errors:

A lib/ directory will only cause pain. Move the code to app/lib/ and make sure the code inside follows the class/filename conventions.

Additionally, there is also:

Don't configure extra paths in autoload_paths or eager_load_paths. That's a hack; follow the conventions! Any directory underneath app/ may contain Ruby code, you don't need to explicitly configure anything.

My questions are:

Is there any truth to these statements that using /app/lib is better than /lib?

Is this only helpful for autoloading Rails-related objects (such as AR models, controllers, jobs, etc)? Or will it also help POROs?

Is there only a specific context in which these comments make sense?

Horary answered 11/9, 2018 at 20:53 Comment(1)
I would argue that not using autoloading is one of the reasons to put external classes into the lib folder. I wouldn't try to make autoloading working with the lib folder. I would always use an explicit require to load features from the lib folder.Denary
A
21

In my experience app/lib is easier to use. You can literally stick in something like Class MathFunction and use it elsewhere (e.g. controllers or modules) with MathFunction.sqrRoot.

To use /lib you need to configure your Rails app with autoload_paths. autoload_paths also need some tweaking to work properly in production. Matz himself discourages autoload because it's in the process of being deprecated.

The only time I've needed to use the lib directory is for making custom rake tasks. Otherwise I stick to app/lib.

Alexandrine answered 11/9, 2018 at 21:5 Comment(2)
Matz withdraw the proposal about autoload, please see end of your linkEijkman
@Alirezamohagheghi is correct Matz withdrew his proposal. The answer is still relevant though typically I reserve /lib for custom rake tasks that are rails specific, and app/lib for code I want to reuse.Alexandrine
E
1

The best practice to accomplish that nowadays is to move that code to app/lib. Only the Ruby code you want to reload, tasks or other auxiliary files are OK in lib. If you do that, there is nothing to configure, it works automatically, and your code base remains simple and standard.

source: Xavier Noria, Zeitwerk’s creator


A lib/ directory will only cause pain. Move the code to app/lib/ and make sure the code inside follows the class/filename conventions.

source: Sidekiq’s Problems and Troubleshooting


Example of Rails project using this convention - Mastodon

Exciter answered 4/7 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.