Single instance variables in controllers

I’m curious about the “single instance variable in the controller” guideline mentioned in the workshop. @halogenandtoast: you mentioned that you were experimenting with it when the video was recorded – how has your experience been so far? Some apps have complex views that include sets of heterogeneous data, which I suspect may end up being grouped in a class (like the Dashboard one in the video) whose only purpose is aggregating those datasets in order to be passed to the view. In your experience, is that always the case? What are the main benefits over aggregating the data sets in the controller, testability or ease of maintenance in the controller perhaps?

3 Likes

Hey @raul,

My experiences have been really positive. I do find that there are objects which end up representing the state of the view and I think this is a fantastic problem to have. I think that views in rails aren’t represented by a class by default is a problem. As you’ve correctly guessed this makes testing the controller substantially easier (if you write controller tests). It also puts the logic (which is very specific to the view and that the controller doesn’t care about) in a class you can test individually. All in all it creates more classes, but it creates them in the best kind of way.

1 Like

Wow, thank you very much for confirming it @halogenandtoast – the idea sounded great but nothing beats some time of real-world experience!

As in any new practice we adopt, I guess you had to make a few initial choices (e.g: "where do I put these new classes and their tests?, “should I use a 1-1 view-class mapping?” or “should I also create new classes for partials that share common data structures?”) and iterate along the way, would you mind elaborating a bit more about this or, perhaps, sharing one of the more complex examples you’ve been working on so far?

Sorry if this can consume too much time for you @halogenandtoast but I’m really curious about this topic and I’d love to learn from your experience. If a response ends up being too long, perhaps could be a topic for a future “Weekly iteration” episode @benorenstein?

2 Likes

Definitely a possibility.

2 Likes