Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading of rails lib

Tags:

People also ask

What is Rails eager loading?

Eager loading lets you preload the associated data (authors) for all the posts from the database, improves the overall performance by reducing the number of queries, and provides you with the data that you want to display in your views, but the only catch here is which one to use.

What is autoloading in Rails?

Rails automatically reloads classes and modules if application files in the autoload paths change. More precisely, if the web server is running and application files have been modified, Rails unloads all autoloaded constants managed by the main autoloader just before the next request is processed.

What is Zeitwerk?

Zeitwerk is an efficient and thread-safe code loader for Ruby. Given a conventional file structure, Zeitwerk is able to load your project's classes and modules on demand (autoloading), or upfront (eager loading).

What is autoload in Ruby?

Ruby has an in-built module autoload, which comes into action whenever a specific module or a class is accessed or called upon from the parent or calling class or module. Upon receiving a call, this module registers the corresponding file path to the called module.


It looks like this issue will be solved in Rails 4: http://blog.plataformatec.com.br/2012/08/eager-loading-for-greater-good/ but until then, I'm wondering how to eager-load modules/classes in my /lib.

In IRB it appears that they are loaded on-demand the first time I try to access:

Foo::Bar.constants
=> []

Foo::Bar::Service
=> Foo::Bar::Service

Foo::Bar.constants
=> [:ServiceBase, :Service]

I have several other classes in that module, and my code depends on being able to look them up using Foo::Bar.const_defined? at runtime - how do I ensure all Foo::Bar's classes get loaded at startup?

I'm already using config.autoload_paths += %W(#{config.root}/lib) in application.rb.