# How Module Autoloading Works in Ruby and Rails

*Published on June 14, 2023*

Tags: Rails Internals

---


Typically, you use&nbsp;[`require`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-require)&nbsp;to load libraries and modules your Ruby code needs.

```ruby
require 'net/http'
```

The Ruby interpreter loads the required code as soon as it comes across the&nbsp;`require`&nbsp;method.

However, often you may not want to load all the dependencies as soon as possible. If they take a long time to load, it can slow down your application initialization process. This is really important during local development and also when running tests. You want to load, run, and test the app as quickly as possible, without loading any code that you won't use.

In these cases, to speed up the initialization process, Ruby provides the&nbsp;[`autoload`](https://ruby-doc.org/3.2.0/Kernel.html#method-i-autoload)&nbsp;method that lazily loads the specified modules. In addition, Rails overrides and abundantly uses this method to set up various sub-frameworks like ActiveModel and ActiveStorage, etc.

The first time I came across autoloading, I was pretty baffled, as I hadn't seen something like that in C# and JavaScript. After a little bit of digging, it turned out to be a simple and pretty useful concept.

**So, what does the**&nbsp;**`autoload`**&nbsp;**method do, and how does it work?**

Let's try to understand Ruby's version first.

## Autoloading in Ruby

The&nbsp;`autoload`&nbsp;method takes two arguments:&nbsp;**Module Name**&nbsp;(can be either a string or a symbol) and&nbsp;**filename**&nbsp;(string). It registers the filename to be loaded the first time that module is accessed.

```ruby
autoload :Payment, '/lib/modules/payment.rb'
```

What it means is that Rails won't load the&nbsp;`payment.rb`&nbsp;script until you actually need it. It will only load it when you first use the&nbsp;`Payment`&nbsp;module in your codebase.

Using&nbsp;`autoload`&nbsp;allows you to speed up the initialization of your library by lazily loading the modules that your code depends on. It won't load the library or framework code you don't need.

## Autoloading in Rails

Ruby on Rails provides its own&nbsp;[`autoload`](https://api.rubyonrails.org/classes/ActiveSupport/Autoload.html#method-i-autoload)&nbsp;method via its Active Support framework. It allows you to load modules based on&nbsp;[Rails naming conventions](https://github.com/fxn/zeitwerk#file-structure), by automatically guessing the filename based on the module name.

```ruby
module ActiveModel
  extend ActiveSupport::Autoload
  
  # autoload this module from the 
  # active_model/secure_password.rb file
  autoload :SecurePassword
end
```

In this example, Rails will look for the&nbsp;`SecurePassword`&nbsp;module in the&nbsp;`active_model/secure_password.rb`&nbsp;file.

Here's the simplified implementation of this method in Rails.

```ruby
def autoload(const_name, path)
  unless path
    full = [name, const_name.to_s].compact.join("::")
    path = Inflector.underscore(full)
  end

  super const_name, path
end
```

If the&nbsp;`path`&nbsp;is not provided, Rails guesses the path by joining the constant name with the current module name and generating its underscored and lowercase form. Finally, it calls Ruby's&nbsp;`autoload`&nbsp;method by calling&nbsp;`super`&nbsp;and passes the module name and the generated path.

For example, consider the following code:

```ruby
module ActiveModel
  extend ActiveSupport::Autoload

  autoload :API
  autoload :Name, "active_model/naming"
end
```

The first time you use the&nbsp;`API`&nbsp;module, Rails will load it from&nbsp;`active_model/api.rb`&nbsp;file. In contrast, when you need the&nbsp;`Name`&nbsp;class, it will be loaded from the&nbsp;`active_model/naming.rb`&nbsp;file.

### Autoloading Multiple Modules From the Same Directory

If multiple modules live under a common folder structure, you can also use the&nbsp;`autoload_under`&nbsp;helper.

```ruby
module ActionController
  extend ActiveSupport::Autoload

  autoload :API
  autoload :Base

  autoload_under "metal" do
    autoload :Cookies
    audoload :Flash
  end
end
```

The&nbsp;`Cookies`&nbsp;and&nbsp;`Flash`&nbsp;modules will be loaded from&nbsp;`action_controller/metal/{cookies/flash}.rb`&nbsp;files.

### Autoloading Multiple Modules in the Same File

If a single file contains multiple modules that you want to autoload, use the&nbsp;`autoload_at`&nbsp;helper. For example, the&nbsp;`action_view/buffers.rb`&nbsp;file contains two modules:&nbsp;`OutputBuffer`&nbsp;and&nbsp;`StreamingBuffer`. To autoload them both, Rails uses the following code:

```ruby
module ActionView
  extend ActiveSupport::Autoload
  
  autoload_at "action_view/buffers" do
    autoload :OutputBuffer
    autoload :StreamingBuffer
  end
end
```

### Eager Load Modules As Necessary

Finally, you can also define a set of modules that need to be eager loaded using the&nbsp;`eager_autoload`&nbsp;method.

```ruby
class Cipher
  extend ActiveSupport::Autoload
  
  eager_autoload do
    autoload :Aes256Gcm
  end
end
```

Then you can eager load the&nbsp;`Aes256Gcm`&nbsp;module by calling the&nbsp;`eager_load!`&nbsp;method (notice the&nbsp;`!`&nbsp;bang)

```ruby
Cipher.eager_load!
```

The original implementation of the&nbsp;`eager_load!`&nbsp;method looped through the modules marked to be eager loaded and simply required them as follows:

```ruby
def eager_load!
  @_autoloads.each_value { |file| require file }
end
```

However, in the latest version of Rails, it's using the&nbsp;`const_get`&nbsp;method to load the constants, see&nbsp;[this PR](https://github.com/rails/rails/pull/44575)&nbsp;for more details.

Anyway, that's all for now. If you're curious to learn the difference between&nbsp;`load`,&nbsp;`autoload`,&nbsp;`require`, and&nbsp;`require_relative`&nbsp;methods, check out this article:

[The Difference Between load, autoload, require, and require\_relative in Ruby 📖](/difference-between-load-autoload-require-in-ruby)[  
](/difference-between-load-autoload-require-in-ruby)

