Rails Autoloading

Rails Autoloading

Autoloading code is a mechanism in Rails that causes frameworks, classes, and code to be loaded automatically on boot. This helps productivity by allowing developers to freely use constants and classes without having to explicitly require them.

An issue arises however that large amounts of code that are not needed for boot are loaded during the boot of an application, or are loaded out of order.

The diagram below shows how files and classes are autoloaded.

diagram image

Problem

Load order dependency issues can happen due to nested class defintions.

In the code snippet below, class A defines a class B. This means that the constant B is now defined. In the diagram above, we see that the un-nested class B depends on the ConstantMissing error to load it during auto-load. However, since A::B is defined, a ConstantMissing hook will never happen as B will resolve to A::B.

class A
   class B
   end
end

class B
end

In particular, from the diagram above, this part never happens.

diagram image