OpenAPITools/openapi-generator

[Ruby] Add support for autload

Closed this issue · 2 comments

Description

In Ruby there are two ways of loading a Class/Module/Gem. One if by eager loading it with require, which will also execute any code present in the file outside of a module or class block (like other requires or any code at all).

The other (lazy-loaded) is by declaring autoload :ConstantName, 'path/to/file'. When using autoload, the first time the constant is called (ex: a Module or Class name), the file referred is loaded.

Lazy Loading can improve bootup performance for CLI applications as only used parts are loaded from the disk. In applications with hundreds of files this does make a difference.

It also benefits Rails applications when loading in development mode, as code is loaded from disk only when required (this is what Zeitwerk does for rails-based code, but the principle is the same an can be used for gems). Still in rails land, it can also help lower rake task start time, as those usually touch only parts of the codebase, if we can use lazy-loading effectively, there is less things we need to load from the disk.

There are some cases where autoload may not be fully desired: When using an app server that uses fork, you may want to eager-load most of the codebase in memory so that when fork is triggered, you can benefit from sharing that to forked process and rely on CoW.

In case of autoload and fork, this can be mitigated by adding manual requires in a before_fork block in the app server configuration file.

This approach is supported by both Puma and Unicorn.

Suggest a fix/enhancement

Switch from require approach to autoload (either by default or as a configuration param).

I agree with this approach. I'm fine with defaulting to require but there should be an option to use autoload or otherwise delay load the API. As a nice to have, it would be interesting if the generator could detect a potentially large generated ruby API and warn/suggest this new option.

In my case, I stumbled upon a client generated from version 5.3.1 that was requiring roughly 6000 files.

I recently did a change in a specific client using autoload which significantly drops memory usage and time to load. Here was that change: xlab-si/intersight-sdk-ruby#14

It seems pretty simple to add here, so I'll put up a PR. I think it will also fix #4690 and obviate #9103.