Read more

How to debug Rails autoloading

Arne Hartherz
January 04, 2018Software engineer at makandra GmbH

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.

Illustration book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
Read more Show archive.org snapshot

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
Posted by Arne Hartherz to makandra dev (2018-01-04 19:44)