Here is a quick and easy way to decorate any object instance in Ruby.
object.singleton_class.instance_eval do | |
attr_accessor :label | |
end |
This is useful if you don't know or care the object type you are working with but would like to add accessor methods to just that instance. This is a very pure decorator because adding accessors does not rely on internal knowledge of the object.
We're just dynamically adding functionality to the instance as we need it.
NOTE: This could clobber existing functionality, so you want be sure you are decorating it with a method name that won't interfere with the object class.
Top comments (0)