If I have a deeply nested set of objects, will “delegate” help me make sense of them?

Imagine you have a Report that is built out of multiple templates and values, where a template is built out of sections, columns and fields:

This is a pretty complex, circular, set of relationships.

And in fact, in situations like this, I would use an Entity Relationship Diagram, which is an old-fashioned way of visualising database schemas, to try and get a handle on what’s going on – as shown here: IMG_3308

What if, when listing your values, you want to show which template it eventually relates to?

The naive implementation would look like this:

But this is pretty ugly. If you want the technical reason, look up the Law of Demeter, but what you’re doing is revealing the structure of your database in your view – so if you change that structure in any way, then your view (and anywhere else that you follow that chain of links) breaks.

However, simplifying it is easy. A quick sprinkling of delegates in your Value class and you are hiding that structure.

And now your view becomes:

So not only is the view much simpler, and easier to understand (and I find view code the hardest of any to read). But also, if you do decide to remove one of those layers in the hierarchy, or add something else in, all you need to do is change the relevant delegate calls in your model and your view remains unchanged.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe