Decorating a class is another way of extending the functionality of a class instead of subclassing. In Ruby there is an elegant way to decorate a class using SimpleDelegator.
Lets say you have a Coffee class and want to decorate the class by adding a Milk and Sugar version of it without subclassing, then you can do so as such in Ruby:
In the example above, you have Coffee class which returns Coffee for ingredients but when you decorate the plain_coffee object with Milk decorator then it returns Coffee,Milk for ingredients. And when we decorate the milk_coffee object with Sugar then it returns Coffee,Milk,Sugar for ingredients.
I found decorating objects very easy in Ruby due to SimpleDelegator as it delegates all methods to the object being decorated that is passed in the contrustor of the decorator. It is able to do so using method_missing available in Ruby which SimpleDelegator uses to invoke the same method on the object being decorated. Compare this with writing a similar decorator in language like Swift or Java where you need to write a Decorator class and then subclass the decorator class for Milk and Sugar coffee:
Purchase a paperback copy or eBook from Amazon, Barnes and Noble or other online retailers.
Image
Ankur અંકુર Patel
Full Stack Ruby on Rails, Frontend Web and native iOS App Developer | Author of "Hands-on Full-Stack Development with Swift" amazon.com/author/ankurpatel