Last Updated: February 25, 2016
·
383
· mrkjlchvz

How I implement Decorator Pattern in Ruby

I'd like to know how you guys implement decorator pattern. Here's how I do it.

Given this class:

class Sender
     def talk
          puts "Hello world!"
     end
end 

How do we add a logging mechanism in such a way that we will not alter the code of the above class?

This is how I do it:

  • Create a new class.
class LogSender
     def initialize(sender)
          @sender = sender
     end

     def send
          #log something here
          @sender.talk
     end
end