Decorator Object Pattern for Rails

One of the challenges with any web application as it grows is corralling code into understandable units.

This need drives many people to use a decorator (or presenter) pattern to collect the display logic associated with underlying models into one object to us in the view.

I had the same issue in the App that runs, and after examing the various simple implementations and the two main gems, draper and active_decorator.

My objections to most were the use of ‘magic’ to determine the view context, or the use of method_missing or other dynamic methods to delegate method calls to the underlying model.

In the end I settled on rolling my own.

The main difference in my implementation is that the methods to be passed through to the model are defined at compile time using define_method.

This ensures that the methods exposed via the decorator are only those required in the view.

In practice, I found that this approach had an interesting side-effect. When adding a method I thought about the consequences of access. Was it really needed. Was there a better way to get this information to the view?

The code is over on Github.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s