Rails 3.2 Autoloading, In Theory

While I was digging into the implementation of autoload_paths and company, I started out in edge rails and saw some of he work under way for 3.2. The material seemed relevant since my last article is shortly to become a little obsolete, but it carries the heavy disclaimer that I haven’t had to fight with this yet – I’ve just read the source.

Rails 3.2 will introduce lazier autoloading. It will only reload files if some file has been changed. I initially read this as saying that only changed files would be reloaded, but on further inspection (and more careful reading of the changelog), all it’s doing is changing the triggering mechanism for the same thing it was doing before.

Most things actually work the same – only the first and last steps change. Our last step (to_cleanup) in the < 3.2 system was to clear out the autoloaded constants. instead, we have a first step (to_prepare) which examines all the autoloadable files to see if any have changed. If any file has changed, we resume with the step as before – clear out the constants so that they will trigger autoloading again.

The process is optional, controlled once again by a config variable.


Here’s the process in another form

`reload_classes_only_on_change = false’ (old behavior)

  1. Do the request, loading constants as needed
  2. Clear the autoloaded constants

`reload_classes_only_on_change = true’ (new behavior)

  1. Clear the autoloaded constants if any potentially loadable file has changed
  2. Do the request, loading constants as needed

It wasn’t entirely true to say ‘any potentially loadable file’ The new process has it’s own set of config variables. However, our old friend autoload_paths gets appended to it down in the bowls of Rails. This means that:

  1. You probably don’t have to configure anything new
  2. You can’t stop it from watching those paths either (short of turning the whole feature off)


In truth, however, you aren’t stuck with anything: the file watcher itself is completely configurable. Just set config.file_watcher to your own class. Look up ActiveSupport::FileUpdateChecker for an example and documentation. Of course, it’s less likely to be ‘your own class’ than a class optimized for your platform, provided by a gem.

Fewer Restarts?

The file_watcher gets added to an array of reloaders. The one of those reloaders watches the routes file. Meanwhile, the database schema gets added to watchable_files. There might be fewer reasons to restart your server in the future.

Posted Friday, January 13th, 2012 under Essay.

Comments are closed.