Skip to content

Instantly share code, notes, and snippets.

@carlosramireziii
Last active April 12, 2018 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carlosramireziii/0fab7e6aa788731f193f87dcef179112 to your computer and use it in GitHub Desktop.
Save carlosramireziii/0fab7e6aa788731f193f87dcef179112 to your computer and use it in GitHub Desktop.
An example of using the Decorator pattern for filtering out profanity
class CleanPost < SimpleDelegator
def title
# calling `super` here will return the value of the #title from the original object
Profanity.filter(super)
end
end
# usage
unclean_post = Post.new(title: "foo BAD WORD bar")
unclean_post.title # => "foo BAD WORD bar"
clean_post = CleanPost.new(unclean_post)
clean_post.title # => "foo *** *** bar"
@carlosramireziii
Copy link
Author

A "Decorator" is an object which takes in another object and extends / alters / "decorates" that object's data.

In this example, we create a decorator called CleanPost which takes in a regular Post and overrides it's title method to be filtered. This is all facilitated by Ruby's built-in SimpleDelegator object.

Here's a good resource for learning more about using it:
https://blog.encoredevlabs.com/feature/ruby/decorator/simpledelegator/2017/01/20/easy-decorating-in-ruby.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment