View Models

Silly Tagline

The missing glue between the letters in ruby on rails' MVC.

Serious Tagline

The missing glue between the layers in ruby on rails' MVC.

But why? Let me tell you a story of high adventure

During writing a music community platform with multiple different profile types – in our case bands, normal members, venues, and labels – it occurred to us that type specific methods used in views were hard to place.

As a simple example: A method that generates a name that is displayed on top of the page, like "Rudy's Randy Rockers", or a similarly realistic band name.

The problem

For bands that needed to be just the band name, for members the name and surname, for labels the name along with the amount of bands under contract. Requirements that are easily fulfilled, for an engineer with a few tricks up his sleeves. Or so it seemed.

A long and arduous journey

First, we tried putting it into models, but that violated the MVC principle and we didn't feel to good about sticking view code into the model. Besides, all view helpers are pretty inaccessible in the model. And for a good reason too!

Even after sticking the code into a helper, thus into the view, this didn't feel much better either, as we had to check for the type of the model. That resulted in a case of case statements which we do not speak about too much nowadays. Even bringing it up here caused me to cringe. Masochism? Yes. Polymorphism? Sadly, no.

P.S: Rule number one. We do not speak about case statement club. Ever.

The big question

So, where to put this view specific, model-type dependent code?

The solution

Enter view models, the public face of the normally shy models.

Bag o' bits