Ruby rails: autoload

From wikinotes
Revision as of 16:34, 19 April 2020 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

A default configuration autoloads all ruby-subdirectories from {project}/app/**.

This means you can just type code, without require statements.

model = MyNamespace::MyModel.new

Documentation

official docs https://guides.rubyonrails.org/v5.2/autoloading_and_reloading_constants.html
blog: rails autoloading hell (rails<=5) https://www.urbanautomaton.com/blog/2013/08/27/rails-autoloading-hell/
blog: rails constant lookup (rails<=5) http://cirw.in/blog/constant-lookup.html

Rails <= 5

The idea of autoloading marries a module/class hierarchy, and file naming conventions.

# filepath:  {autoload_path}/module_a/module_b/module_c.rb
A::B::C.new()
  • You can inspect an object's resolved nested path using Module.nesting.
module A
  module B
    class C
      def print_nesting
        puts Module.nesting   # [A::B::C, A::B, A]
      end
    end
  end
end

Rails 6+

Rails 6+ uses ruby zeitworks for autoloading.