How to debug Rails autoloading

Posted . Visible to the public.

ActiveSupport::Dependencies takes care of auto-loading any classes in development. This is usually useful, but when you run into issues with the Rails autoloader, you should take a look at what it's doing.

For me this was useful in an "exciting" case of auto-loading classes inside a thread which caused the application to stop responding.

Rails 4.x

ActiveSupport::Dependencies includes logging support. It is easy to use:

ActiveSupport::Dependencies.logger = Rails.logger

Rails 5+

Logging support was removed Show archive.org snapshot for Rails 5. You need to manually patch yourself into the module's code.

Here is a dirty solution that works.

ActiveSupport::Dependencies.singleton_class.prepend(Module.new do
  def load_missing_constant(*args)
    Rails.logger.debug "#{__method__}(#{args.map(&:inspect).join(', ')})"
    super
  end
end)

Example output:

>> Page::Version
load_missing_constant(Object, :Page)
load_missing_constant(Page, :Version)
=> Page::Version
Arne Hartherz
Last edit
Arne Hartherz
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2018-01-04 18:44)