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.
Build a delegator for a Ruby class by using Ruby’s SimpleDelegator.
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.
# 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
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.
Can be found on the solutions branch on github.