Name conflict between controller name and presenter namespace

坚强是说给别人听的谎言 提交于 2019-12-10 11:41:44

问题


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)

回答1:


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:

@presenter = ::Pages::HomepagePresenter.new(current_user)


来源:https://stackoverflow.com/questions/6884802/name-conflict-between-controller-name-and-presenter-namespace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!