Last active
April 12, 2018 00:59
-
-
Save carlosramireziii/0fab7e6aa788731f193f87dcef179112 to your computer and use it in GitHub Desktop.
An example of using the Decorator pattern for filtering out profanity
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 regularPost
and overrides it'stitle
method to be filtered. This is all facilitated by Ruby's built-inSimpleDelegator
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