Decorator Pattern in Ruby
In object-oriented programming, the decorator pattern allows behaviour to be added to individual objects, without affecting the behaviour of other objects from the same class.
It’s one of the design patterns
A design pattern in software engineering is a proven solution to a common coding problem. It’s a way of organizing code that makes it more efficient, reusable, and easier to maintain. Essentially, it’s a template for structuring your code.
Decorator pattern in Ruby
Decorator pattern is particularly useful in Ruby for enhancing objects with additional methods. Ruby’s standard library provides the `SimpleDelegator` class to achieve this.
What is SimpleDelegator?
`SimpleDelegator` is a class from Ruby’s standard library that provides delegation. It works by wrapping an object and delegating method calls to the wrapped object. This allows us to extend the functionality of the wrapped object without altering its original implementation.
Example: Decorating a Book Class
Let’s look at a very simple example using a Book class and a decorator.
class Book
attr_reader :title, :author
def initialize(title, author)
@title = title
@author = author
end
def description
"#{title} by #{author}"
end
end
#####
class BookDecorator < SimpleDelegator
def fancy_description
"*** #{description} ***"
end
endIn this example:
Get Egemen Öztürk’s stories in your inbox
Join Medium for free to get updates from this writer.
We got 2 things going on.
1. Book is a basic class with title and author attributes and a `#description` method.
2. BookDecorator extends SimpleDelegator and adds a `#fancy_description` method that introduces new behavior without altering the original Book class.
Using the Decorator
book = Book.new('1984', 'George Orwell')
# Decorate the book object here
decorated_book = BookDecorator.new(book)
decorated_book.description
# => "1984 by George Orwell"
decorated_book.fancy_description
# => "*** 1984 by George Orwell ***"








