Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

autoload with namespaces/submodules

Tags:

ruby

autoload

I'm using modules as namespaces in ruby. How would I go about autoloading...something like autoload :"App::ModuleA", 'app/module_a that doesn't throw a "must be constant name" error?

like image 456
Aaron Yodaiken Avatar asked Jun 02 '10 17:06

Aaron Yodaiken


1 Answers

You need to pass a symbol to autoload (probably a typo in your question), and call it on the parent of the constant, like:

App.autoload :ModuleA, "app/module_a"

Note that this works for nested levels too. Say that in app/module_a you have:

module App::ModuleA
  autoload :Inner, "path/to/inner"
end

When Ruby encounters App::ModuleA::Inner, it will first attempt to access ModuleA, succeed by autoloading it, and only then attempt Inner, which succeeds also because it now knows where to autoload it.

like image 99
Marc-André Lafortune Avatar answered Nov 13 '22 08:11

Marc-André Lafortune