Rails controllers and OOP

I have written a much better explanation, please read that instead: Explaining Focused Controller

Rails controllers violate the Single Responsibility Principle. Each “action” has a different responsibility and should be contained in a separate object. Controllers are also hard to unit test, so we end up using slow “functional tests”.

This realisation lead me to experiment with altering the conventions for controller code, and today I gave a talk on the topic at Railsberry called You Hate Your Codebase & It’s Your Fault.

I wrote a plugin named Focused Controller a while back, as part of this experiment, but have kept quiet about it until now, partly because it was undocumented.

But now I’m ready to announce it and I’m really keen for people to try it out and share their thoughts about this idea. I’ve gone into detail about the problems and solutions in the README, so I won’t repeat that here. Please just check it out!

Comments

I'd love to hear from you here instead of on corporate social media platforms! You can also contact me privately.

Pavel Forkert's avatar

Pavel Forkert

It would be cool, it that would be available in Rails 4.0 out of the box!

Alexey Muranov's avatar

Alexey Muranov

I personally do not understand very well why controller actions need to be object methods and not simply namespaced functions (i know they would be object methods anyway). Is there other use for instance variables than to store the request parameters and memoize the values used in the views?

Wouldn't it be simpler to view each controller action as a function that gets a "request" object, does something to the models, and returns a "response" object, possibly first initializing some "helper" objects?

Update: i am wondering about a possibility of the following realization of MVC: model -- class, controller -- module, view -- collection of templates (or maybe a class).

julian7's avatar

julian7

Yep, FocusedController should be in Rails 4.0, keeping the old controller format as soon to be obsoleted.

Etienne Massip's avatar

Etienne Massip

Agreed, what about famous RoR magic?

I used to like the way V and C mixed together in RoR, it's also kind of the way how JSF works.

One class per action is overkill IMHO.

Alexey Muranov's avatar

Alexey Muranov

Here is a situation i've encountered where the usual un-focused controllers look a bit unnatural. I have a nested resource controller, which is not going to have the `index` action because the main resource controller `show` action is going to show the nested resource index. I have an impression that my controllers overlap here. I also anticipate some code duplication.

Add your comment