使用命名空间/子模块自动加载

发布于 2024-09-03 21:51:50 字数 121 浏览 4 评论 0原文

我在 ruby​​ 中使用模块作为命名空间。我将如何进行自动加载......像 autoload :"App::ModuleA", 'app/module_a 这样的东西不会抛出“必须是常量名称”错误?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

黎歌 2024-09-10 21:51:50

您需要将一个符号传递给 autoload (可能是问题中的拼写错误),并在常量的父级上调用它,例如:

App.autoload :ModuleA, "app/module_a"

请注意,这也适用于嵌套级别。假设在 app/module_a 中你有:

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

当 Ruby 遇到 App::ModuleA::Inner 时,它会首先尝试访问 ModuleA,成功通过自动加载它,然后才尝试Inner,它会成功,因为它现在知道在哪里自动加载它。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文