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)


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 =