March 10 - Using SimpleDelegator in Ruby to Implement the Decorator Pattern
There are a number of ways to implement the decorator design pattern in Ruby. In this guide we're going to examine how we can leverage the SimpleDelegator tool in Ruby to add additional functionality to a class.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise
Video locked
This video is viewable to users with a Bottega Bootcamp license

Summary

Build a delegator for a Ruby class by using Ruby's SimpleDelegator.

Exercise Description

Implement a delegator for a Ruby class using Ruby's SimpleDelegator process to add functionality to a class without having to add code to the class itself.

Examples

# A standard Ruby class that has a name initializer attribute
invoice = Invoice.new('Kristine Hudgens')

# A decorator that inherits from SimpleDelegator
# and takes in an instance of the Invoice class
decorated_invoice = InvoiceDecorator.new(invoice)

# invoice_month needs to be a method in the class
# but it can be called by the delegate
decorated_invoice.invoice_month # => 9

# last_name is a method in the decorator
# that splits the class name attribute
decorated_invoice.last_name # 'Hudgens'

# this shows that you can access the object
# passed to the decorator with the __getobj__ method
decorated_invoice.__getobj__ == invoice # => true

Real World Usage

The decorator pattern is a common design pattern. Ruby offers a number of processes for implementing the pattern and the SimpleDelegator is one of the most popular. This is critical when it comes to building clean programs and following best practices.

Test Cases

Code File