控制器名称和演示者命名空间之间的名称冲突
我正在使用演示者模式,并且似乎遇到了不一致的类命名冲突。我有一个带有主页方法的页面控制器,我想让该方法使用 Pages::HomepagePresenter 类,但最终出现错误:
uninitialized constant ActionController::Caching::Pages::HomepagePresenter
# ./app/controllers/pages_controller.rb:3:in `homepage'
# ./spec/requests/pages_spec.rb:14:in `block (5 levels) in <top (required)>'
假设问题出在演示者的页面控制器和页面命名空间上,但有当使用主页控制器和演示者的主页命名空间时,似乎不是问题。
我错过了什么吗?以下是我尝试过的应用程序行为组合:
# Ideal, but this breaks with the aforementioned error
presenters/pages/homepage_presenter.rb (class Pages::HomepagePresenter)
controllers/pages_controller.rb (class PagesController)
# Works
presenters/page/homepage_presenter.rb (class Page::HomepagePresenter)
controllers/pages_controller.rb (class PagesController)
# Workes; I would expect this to break
presenters/homepage/index_presenter.rb (class Homepage::IndexPresenter)
controllers/homepage_controller.rb (class HomepageController)
I am using the presenter pattern and am seemingly running into inconsistent class naming conflicts. I have a pages controller with a homepage method and I'd like to have that method use the Pages::HomepagePresenter class, but end up with the error:
uninitialized constant ActionController::Caching::Pages::HomepagePresenter
# ./app/controllers/pages_controller.rb:3:in `homepage'
# ./spec/requests/pages_spec.rb:14:in `block (5 levels) in <top (required)>'
Assuming the problem is with the Pages controller and Pages namespace for the presenter, but there doesn't seem to be an issue when using Homepage controller and Homepage namespace for the presenter.
Am I missing something? Below are the combinations I've tried with how the app behaves:
# Ideal, but this breaks with the aforementioned error
presenters/pages/homepage_presenter.rb (class Pages::HomepagePresenter)
controllers/pages_controller.rb (class PagesController)
# Works
presenters/page/homepage_presenter.rb (class Page::HomepagePresenter)
controllers/pages_controller.rb (class PagesController)
# Workes; I would expect this to break
presenters/homepage/index_presenter.rb (class Homepage::IndexPresenter)
controllers/homepage_controller.rb (class HomepageController)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我刚刚发布了一个 类似问题,然后找到了解决方案:
Pages 模块已在ActionController::缓存。当您使用常量“Pages”时,rails 会猜测您引用的是此名称空间,但在其中找不到 HomepagePresenter,因此会抛出错误。
通过在顶级名称空间前加上
::
前缀来显式指定顶级名称空间来修复此问题,如下所示:I just posted a similar question and then figured out the solution:
The Pages module is already defined in ActionController::Caching. When you use the constant "Pages", rails guesses you're referring to this namespace, but doesn't find HomepagePresenter in it, so it throws an error.
Fix it by explicitly specifying a top-level namespace by prefixing it with
::
, like this: