Name conflict between controller name and presente

2019-09-04 17:40发布

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条回答
地球回转人心会变
2楼-- · 2019-09-04 18:02

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)
查看更多
登录 后发表回答