问题描述
我使用了presenter模式,看起来运行不一致的类命名冲突。我有一个页面控制器与首页方法,我想有该方法使用Pages :: HomepagePresenter类,但最终出现错误:
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)>'
假设问题是用于演示者的Pages控制器和Pages命名空间,但是对于演示者使用Homepage控制器和Homepage命名空间时似乎没有问题。
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)
推荐答案
我刚刚发布了,然后找出解决方案:
I just posted a similar question and then figured out the solution:
Pages模块已经在ActionController :: Caching中定义。当你使用常量Pages时,rails猜测你是指这个命名空间,但是没有找到HomepagePresenter,所以它会引发一个错误。
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它通过用 ::
前缀明确指定顶级命名空间,如下所示:
Fix it by explicitly specifying a top-level namespace by prefixing it with ::
, like this:
@presenter = ::Pages::HomepagePresenter.new(current_user)
这篇关于控制器名称和Presenter命名空间之间的名称冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!